I am pretty sure my logic is flowed, so please help:
I have a classic unordered list, where some li values are different (“Hello 1”, “Hello 2”, “Hello 3”) and some li values are the same (the “Hello World” ones).
I also have a MATCH VALUE which is “Hello World” from the data-ANCHOR.
<ul class="traffic" data-ANCHOR="Hello World">
<li>Hello 1</li>
<li>Hello 2</li>
<li>Hello 3</li>
<li>Hello World</li>
<li>Hello World</li>
</ul>
I tried to make a Jquery code that checks every li If the content of the li is the same with my MATCH VALUE (from the data-ANCHOR), write something else instead.
var ANCHOR = $("ul.traffic").data('ANCHOR');
var ANCHORMATCH = $("ul.traffic li a").text();
if(ANCHOR == ANCHORMATCH){
$('ul.traffic li a').replaceWith('hey hey');
}
It does not work, nothing happens.
But if I change the if condition to if(ANCHOR != ANCHORMATCH) – the code replaces all the <li>‘s contents with “hey hey”.
I am a newb but my gut tells me I should use a loop or something.
This code only ever looks at the content of the first
ul.traffic li aelement. You need to useeachto loop over each of them. (In fact, your HTML doesn’t even haveaelements: I’ve modified the code accordingly.)Note also that jQuery will always move
data-ANCHORto bedata('anchor'). It’s probably wise to give the attribute the normal casing (data-anchor).Working jsFiddle