Distinguishing between two same HTML ID elements using Jquery and css in Wordpress

advertisements

I know that is a bad practice to have more than HTML elements having same ID. However such is my situation where I need to specifically modify either of them.

I researched around and found about Jquery method 'document.getElementByID' that returns with the first similar element and lets you change it using css. Using that I wrote the code below but it doesn't work.

$(document.getElementById('it_trending-3')).css({"display":"none"});

I have added this code in my wordpress theme using the CSS-JS-PHP wordpress plugin, created a shortcut from the same and then added the shortcode. Can someone please guide me what and where I went wrong?

Also feel free to suggest a different function that would maybe let me specifically point to each of the same ID elements using maybe indexes. Thanks!


Keep a class to the divs you want to change:

<div>
    <span id="a" class="test">1</span>
    <span id="b" class="test">2</span>
    <span>3</span>
</div>

The Jquery would go like this:

$(function() {
    var w = $("div");
    console.log($('#a').length);
    console.log($('body #a').length);
    console.log($('#a', w).length);
});

$(".test").first().css({"color":"orange"});
//or
$(".test:first").css({"color":"orange"});

But if you want to select any specific element with the class via an index of sorts, then you would need to do it like this:

var x = $(".test");
$(x[1]).css({"color":"orange"});