I have some HTML like
<ul class="sortword">
<li>
<div>ABC</div>
</li>
<li>
<div>DEF</div>
</li>
</ul>
How can I use Javascript to find and click <div>DEF</div> tags
Array.from(document.querySelectorAll('div')).forEach((div) => {
if (div.textContent.trim() === "DEF") {
let evt = new Event('click');
div.dispatchEvent(evt);
}
});
JQuery
Use the :contains selector:
$("div:contains('DEF')").click()
var myList = document.getElementsByClassName("sortword")[0].getElementsByTagName("li")[0];
<ul class="sortword">
<li>
<div>ABC</div>
<div>DEF</div>
</li>
</ul>
You can do this without jQuery by selecting multiple elements and looping through them, but using it will make this a very short and easily readable code snippet. Be sure to include JQuery on your page using a link like
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$( '.sortword li div' ).on( 'click', function() {
console.log( $( this ).text() );
});
$( '.sortword li div' ).each( function() {
$( this ).click();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="sortword">
<li>
<div>ABC</div>
<div>DEF</div>
</li>
</ul>
You can use textContent as illustrated in the following code:
var el = document.querySelectorAll(‘ul li div’), desire;
for (var i = 0; i < el.length; i ++) {
if (el[i].textContent === 'DEF') { desire = el[i]; }
break;
}
Then use can use desire variable later on.
Related
I was having some troubles when trying to set the on click listerner for <li> dynamically. Here is my code to populate the list:
for(var i = 0; i < chatlist.length; i++){
$('<li class="contact"><div class="wrap"><div class="meta"><p class="name">' + contact + '</p><p class="preview">' + preview + '</p></div></div></li>').appendTo($('#contacts ul'));
}
On click listener for selected row:
$('#contacts').on('click', 'li', function() {
var index = $(this).index();
console.log(index);
});
I am using this template. Upon selecting row, I wanted to set the selected <li> tag to
<li class = 'contact active'></li>
I managed to get the selected row index but I not sure how to set the HTML class for selected <li>. Any idea?
I managed to get the selected row index but I not sure how to set the
HTML class for selected <li>. Any idea?
You can just addClass on the click event itself
$('#contacts').on('click', 'li', function() {
$( "#contacts li" ).removeClass( "active" ); //assuming that it has to be removed from other li's, else remove this line
$( this ).addClass( "active" );
});
try this code which add active class and also i add css to check different
$(document).ready(function(){
$('.list li').click(function() {
$( '.list li' ).removeClass( "active" ); // remove active class from all li
$(this).addClass('active'); // add active class for click li
});
});
.active {
color:red;
}
li {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="list">
<li>Test 1</li>
<li>Test 2</li>
<li>Test 3</li>
<li>Test 4</li>
<li>Test 5</li>
<li>Test 6 </li>
<li>Test 7</li>
</ul>
In the click event handler, $(this) will point to the li element which was clicked. So you should be able to assign a class to it like this:
$('#contacts').on('click', 'li', function() {
$(this).addClass("selected"); // Assign the class here
var index = $(this).index();
console.log(index);
});
You can add your jquery logic in such a way that will remove the active class from all li inside contacts id and then add the active class to the li that has been clicked which you can get from the index of the li like:
var clickedLi = $('#contacts ul li')[index];
or use $(this) instead. Please check the attached snippet.
var chatlist = new Array(3);
var contact = 'contact';
var preview = 'preview';
for(var i = 0; i < chatlist.length; i++){
$('<li class="contact"><div class="wrap"><div class="meta"><p class="name">' + contact + '</p><p class="preview">' + preview + '</p></div></div></li>').appendTo($('#contacts ul'));
}
$('#contacts').on('click', 'li', function() {
var index = $(this).index();
$('#contacts ul li').each(function(){
$(this).removeClass('active');
});
$(this).addClass('active');
});
.active{
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="contacts">
<ul>
</ul>
</div>
You can add active class like this :
$(this).addClass('active');
Since I'm new in Java Script, I need to know how can I change list item color or style using Java Script?
For example I have following unordered list in my HTML file:
<ul id="list">
<li>Text1</li>
<li>Text2</li>
<li>Text3</li>
<li>Text4</li>
</ul>
Now when I click on item it should change the color and when clicking next item it will keep the new color of the previous item and change also color of the newly clicked item (example screenshot below):
Try the below solution. This will toggle the click as well.
var ul = document.getElementById("list");
var listItems = ul.getElementsByTagName("li");
for(li of listItems){
li.addEventListener('click', function(){
if(this.classList.contains('active')){
this.classList.remove("active");
} else {
this.classList.add("active");
}
})
}
.active{
color: red;
}
<ul id="list">
<li>Text1</li>
<li>Text2</li>
<li>Text3</li>
<li>Text4</li>
</ul>
Array.from(document.getElementById('list').children).forEach(function(elem){
elem.addEventListener('click', function(e){e.target.style.color = 'red';})
});
EDIT: All the people suggesting jQuery are crazy importing an entire library just to do one little thing
Use addEventListener to bind an event listener function to the element.
// find all the <li> elements
var listItems = document.querySelectorAll('#list li');
// iterate over the <li> elements
listItems.forEach(function (listItem) {
// this function is called for each <li> element
listItem.addEventListener('click', function () {
// as soon as the list item is clicked, change its color to red
this.style.color = 'red';
});
});
<ul id="list">
<li>Text1</li>
<li>Text2</li>
<li>Text3</li>
<li>Text4</li>
</ul>
Or shorter:
document.querySelectorAll('li').forEach(li => li.addEventListener('click', _ => li.style.color = 'red'));
Below is the jquery code to achieve this
$('li').click(function(){
$(this).css('background-color','red');
})
Add/remove color on each click of element,
Here is the working Fiddle
https://jsfiddle.net/jvk3/5Lyx827b/
html
<ul id="list">
<li>Text1</li>
<li>Text2</li>
<li>Text3</li>
<li>Text4</li>
</ul>
Jquery Script
<script>
$(document).ready(function() {
$('li').click(function(event) {
$(this).toggleClass('red');
});
});//end doc ready
</script>
CSS
<style>
.red{
color: red;
}
</style>
is there a better way to write this simple on click script?
as you can she there is a consistent number in each block.
instead of duplicating it another 10 times for 10 different list item, is there a better way?
the content is not in a child of the li. so i cant club all of them with (this)
heres the thing im working on:
$( '.artist_li1' ).click(function() {
$( '.artist_content' ).removeClass( "active" );
$( '.artist_content1' ).addClass( "active" );
});
$( '.artist_li2' ).click(function() {
$( '.artist_content' ).removeClass( "active" );
$( '.artist_content2' ).addClass( "active" );
});
$( '.artist_li3' ).click(function() {
$( '.artist_content' ).removeClass( "active" );
$( '.artist_content3' ).addClass.addClass( "active" );
});
and so on....
You can use ^ attribute selector in jQuery like this:
$( '[class^=artist_li]' ).click(function() {
$( '.artist_content' ).removeClass( "active" );
$( '.artist_content1' ).addClass( "active" );
});
[class^=artist_li] matches elements with class attribute starting with artist_li
UPDATE: Use jQuery instead of $ as according to your provided link, you're using jQuery v 1.12
For more help, see code block below
$(function(){
$("[class^=artist_li]").on('click', function() {
alert($(this).text());
});
});
li {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<ul>
<li class="artist_li1">Click 1</li>
<li class="artist_li2">Click 2</li>
<li class="artist_li3">Click 3</li>
<li class="artist_li4">Click 4</li>
</ul>
</div>
Hope this helps!
You can do for loop:
for(var i = 1; i < 3; i++) {
(function(index) {
$( '.artist_li'+index ).click(function() {
$( '.artist_content' ).removeClass( "active" );
$( '.artist_content'+index ).addClass( "active" );
});
}(i));
}
To give a better / more efficient answer it would be helpful to see your HTML. But I digress, and will suggest the following -
Assuming some HTML structure as follows - You can remove the need for indexing if you work using DOM traversal relative to the clicked element
$(document).on('click', '.artist_li', function(){
$('.artist_content').removeClass('active');
//this will find the child div inside the list element that
//was just clicked. Removing the need for indexing
$(this).children('.artist_content').addClass('active');
});
.active {
color: red;
}
li {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul> <!-- Adding extra class artist_li to illustrate various method -->
<li class="artist_li1 artist_li">
<div class="artist_content artist_content1 active">Content 1</div>
</li>
<li class="artist_li1 artist_li">
<div class="artist_content artist_content2">Content 2</div>
</li>
<li class="artist_li1 artist_li">
<div class="artist_content artist_content3">Content 3</div>
</li>
</ul>
I've got a scenario where (I won't bore you with the details) I need to convert the text of a series of li's into clickable links (all going to the same destination URL). For instance:
<ul class="list-inline">
<li class="link">Australia</li>
<li class="link">Fiji</li>
<li class="link">Oman</li>
<li class="link">Venezuela</li>
</ul>
I'd like for the countries to be converted into clickable links.
Using:
$( ".link" ).each(function() {
$( this ).css( "color", "red" );
});
I can loop through the li's (although ideally I'd like to be able to 'target' the UL and then it's children removing the need for the class="link"...but that's another matter!) and in this instance simply change the colour of the text but I don't know how to change the text into a link.
Any chance someone could give me some pointers please?
Thanks,
craig
You can use html() to write the inner anchor elements without each() using a callback
$('.link').html(function() {
return '' + $(this).text() + '';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="list-inline">
<li class="link">Australia</li>
<li class="link">Fiji</li>
<li class="link">Oman</li>
<li class="link">Venezuela</li>
</ul>
You can use click since you are using jquery
$( ".link" ).click(function(){
//do something here
alert('clicked');
});
https://api.jquery.com/click/
Consider this:
$( ".list-inline li" ).each(function() {
$( this ).css( "color", "red" ).html(''+$(this).text()+'');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="list-inline">
<li class="link">Australia</li>
<li class="link">Fiji</li>
<li class="link">Oman</li>
<li class="link">Venezuela</li>
</ul>
But maybe you do not want real links, but just clickable <li>s?
$('.list-inline').on('click', 'li', function(event) {
alert("Go to link");
})
.find('li').css({cursor:'pointer'});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="list-inline">
<li class="link">Australia</li>
<li class="link">Fiji</li>
<li class="link">Oman</li>
<li class="link">Venezuela</li>
</ul>
You can use callback function of .html() method:
$( ".link" ).html(function(i , oldhtml) {
return "<a href='someref"+oldhtml+"'>"+oldhtml+"</a>"
});
You can use the 'wrapInner' function to do this:
$("ul.list-inline li").wrapInner(function() {
return "<a href='somepage.html'></a>";
});
Although if you have access to the source to change the classes, not sure why you don't just code the links in place...
Is this what you're looking for?
<ul class="list-inline">
<li>Australia</li>
<li>Fiji</li>
<li>Oman</li>
<li>Venezuela</li>
</ul>
$( ".list-inline li" ).each(function() {
$( this ).css( "color", "red" );
var country = $(this).text();
$(this).html(''+country+'');
});
Demo: http://jsfiddle.net/6cjex8b2/
For example, I have HTML like :
<ul id='myul'>
<li>
Link1
<span>something1</span>
</li>
<li>
Link2
<span>something1</span>
</li>
<li>
Link4
<span>something1</span>
</li>
<li>
Link1
<span>something1</span>
</li>
</ul>
You can see href = http://domain.com/link1 is repeated. So, I want remove one of theme, and keep only one. That mean I have HTML like :
<ul id='myul'>
<li>
Link1
<span>something1</span>
</li>
<li>
Link2
<span>something1</span>
</li>
<li>
Link4
<span>something1</span>
</li>
</ul>
How can I do that with jquery?
Here's the first way that came to mind:
$(document).ready(function(){
var urls = {};
$("#myul a").each(function() {
if (this.href in urls)
$(this).closest("li").remove();
else
urls[this.href] = true;
});
});
Demo: http://jsfiddle.net/CBhF6/
That is, loop over all of the anchor elements within the ul, and test if the current one has an href that you've already seen - if so delete it, otherwise make a note of the href.
You can use $( "li" ).get( -1 )
as long as it is the last one
Try this:
var lnkHash = {};
$('li > a').each(function(){
if(lnkHash[this.href])
{
$(this).closest('li').remove();
} else
{
lnkHash[this.href] = 1;
}
});
http://jsfiddle.net/c4zVk/1/
Try:
var url = [];
$("#myul").find("li").each(function(){
var href = $(this).find("a").attr("href");
if(url.indexOf(href) >= 0){
$(this).remove();
}
else{
url.push(href);
}
});
Fiddle here.
Try this:
$(function(){
$('#myul a').each(function(){
var currHref = $(this).attr('href');
$('#myul').find('a[href="' +currHref +'"]').each(function(index){
if(index > 0) {
$(this).closest('li').remove();
}
});
});
});
http://jsfiddle.net/rKpaK/2/