6. Clarification on how $(this) works


#1

$(document).ready(function() {
    $('#text').click(function() {
        $(this).addClass('highlighted');
        });
    });

After finishing this exercise, I wanted to try something out, trying to understand how $(this) is executed. I added an extra

to the html tab with the id "text," thinking that the .addClass would apply to both div's. It only applied to the middle div, and I don't understand why.

Here's the HTML:

	<body>
        <div id="title" class="highlighted">I'm highlighted!</div>
        <div id="text">Highlight me, too!</div>
        <div id="text">just some more text</div>
	</body>

#2

@frankforeal,
Could you re-edit your Post
so the HTML-code which you added is visible......??


#3

@frankforeal,
An id Attribute should be unique on your document.
if you attach an =click= Eventhandler to an id attribute
the attachment is only done for the 1st appearance in the DOM.

If you want both HTML-Element's attached to the specific =click= Eventhandler
you will have to use the class Attribute....

$(document).ready(function() {
    $('.text').click(function() {
        $(this).addClass('highlighted');
        });
    });

and

<body>
    <div id="title" class="highlighted">I'm highlighted!</div>
    <div class="text">Highlight me, too!</div>
    <div class="text">just some more text</div>
</body>