My HTML looks like this:
<ul>
<div class="topmsg"></div>
<li>
<div id="message"></div>
....</li>
....</ul>
and this list is repeated several times
I could get the div inside the li like this:
li.children('div#message').hide();
Any ideas on how to get the topmsg using jquery or JS?
Ignoring the problems with your HTML.
As you have an ID on the div you want to select, you should just be able to use the # id selector.
$('#topmsg')...
If you have multiple things with the id of topmsg then you really need to reform your HTML so that you don't.
Id is short for "identifier" and should be unique in a document - it is used to uniquely identify the node.
EDIT after topmsg changed from id to class:
Having changed topmsg to be a class, then once you have the LI that contains the message you're interested in you can traverse it with a parent and then a find.
E.g.
// Get the LI that contains the message DIV
var messageLi = $('#message').parent();
// Hide it
messageLi.hide();
// Get the 'topmsg' relating to that LI
messageLi.parent().find('.topmsg').hide();
Use this code, it will get the div relative from the li.
var topmsg = $(li).parent();
Related
I'm trying to web scrape https://liquipedia.net/dota2/Admiral this page for all the <li> tags that are inside an <ul> tag that again is within a div with class mw-parser-output that has the title property. (I think that is what they're called in the HTML world? Like <tag property="...">).
What would be the most elegant, simple way to do this with Cheerio? I know I could do this with some for loops and stuff, but if there was a simple way to do this, my code would be a lot cleaner.
I'm sure glad Cheerio is like jQuery. A simple selector like this should do:
const li = $('div.mw-parser-output > ul > li[title]').toArray(); // Optionaly turn selected items into an array
Explanation of the CSS selector:
div.mw-parser-output div makes sure the element is that. The dot signifies that the selector is a class.
> Points to the immediate child
ul Simple ul tag
li[title] Any li tag, but it needs to have the title attribute.
Then we turn the result into an array so it become usable.
It's a simple as that.
You could also get an array of the text of each li element with the following:
const arrayOfLiTexts = li.map($el => $el.text());
https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
const elements = $('div[title].mw-parser-output ul li').toArray();
I'm quite new to javascript and JQuery programming. Usually, to access elements I give them an id, so I can get them like $("#"+id).blabla().
But now I need to dynamically create a div, and access elements inside it.
Something like
<div id="automaticallyGeneratedId">
<div ???></div> <!-- first div -->
<div ???></div> <!-- second div -->
</div>
What are the best practices to access and identify each of the inner divs?
I generate another id for them?
Or what?
I don't have the theory of selectors fully clear.
edit: modified the question from identifying a single inner div to identifying divs amongs many of them
You can maintain a pattern when you're generating id. For example:
if you always generate id like: myid1, myid2,myid3...
<div id="myid1">
<div></div>
</div>
<div id="myid2">
<div></div>
</div>
......
then you can try:
$('div[id^=myid]').find('div').foo();
OR
$('div[id^=myid] div').foo();
Here, ^= is start with selector, so div[id^=myid] will select div whose id start with myid.
You can also use Contain word selector which is ~= and use like $('div[id~=myid]'). This will select div with id contains word myid.
Instead of id if you want to use other attribute eg. name then change selector like:
$('div[name^=myid]') or $('div[name~=myid]').
It's usually a good practice that if you already have a reference to that outer div to just search from there using find.
You can give it an id, or if you want to use a more general approach you can use classes.
<div class="subdiv">...
$('#automaticallyGeneratedId').find('div.subdiv')
Usually, when you create them, you can assign event handlers and the likes straight on them. Like this:
var div = $( '<div></div>' );
div.on( 'click', function() {
// Do something when the generated div is clicked
});
// Then, add it to the DOM
$( 'body' ).append( div );
You don't need to bother selecting them with ID or classes, they're already available in your code.
Another way is to use event bubbling to handle newly created elements of the same class. A good link about this is this one: http://beneverard.co.uk/blog/understanding-event-delegation/
Many ways you can create an element and give him an Id or Class, or use the DOM to access it..
$("html").prepend('<div id="foo"></div>');
$("#foo").doSomething();
another way
$("#automaticallyGeneratedId").find("div").doSomething();
To access the div in the element with the id:
$("#automaticallyGeneratedId div").whatever
If you cache the divs you could use something like:
var myDiv1Child = $('div', myDiv1);
Create a delegated listener and within the listener you can find the element by doing this
//If a div inside the parent is clicked then execute the function within
$('.PARENT_CLASS').click("div", function(){
//This variable holds all the elements within the div
var rows = document.querySelector('.PARENT_CLASS').getElementsByTagName('div');
for (i = 0; i < rows.length; i++) {
rows[i].onclick = function() {
console.log(this); //The element you wish to manipulate
}
}
});
I want to select the following three values from the HTML file either by Jquery or Javascript.
class "class1" href value
class "class1" inner text value (PersonA in the example code)
class "Title" inner text value (Accountant in the example)
How can I select all the data of li node by node as? I am lost :(
<ol id="result-set">
<li id="v-0">
<div class="result-data">
..
<h2>
<a class="class1" href="">PersonA</a>
</h2>
<dl class="basic">
<dt>Title</dt>
<dd class="title">Accountant</dd>
....
</dl>
</div>
</li>
<li id="v-1">
...
</li>
.....
To get "PersonA": $('#v-0 h2 a').html();
To get href of that link: $('#v-0 h2 a').attr('href');
To get "Accountant": $('#v-0 dl dd').html();
You can modify the id ("v-0") at the start of the selector to choose a particular "row" of your data set.
With jQuery, you can do something like this:
$("#result-set li").each(function() {
var $currentLi = $(this),
$class1link = $currentLi.find("a.class1"),
class1href = $classAlink.attr("href"),
class1content = $classAlink.html();
// do something with values
});
The .each() method will process each li element. Within the callback to .each() the variable $currentLi is a jQuery object holding that li (set from $(this) where this is the li element itself). The .find() method is used to find the anchor element within the li and then its href and content are retrieved.
The "Accountant" you asked about is one item in a definition list, so you'd probably want to loop through that list with another .each() statement nested inside the one above.
You don't make it clear how you want to use the values, but this should get you started. For further details about the various jQuery methods I've mentioned check the jQuery API.
document.getElementById(Id).value
returns value of element with specific id. in jquery:
$("#id").val()
by class $(".yourClass").val()
to get attribute value use attr("attributeName") for example $(".class1").attr('href').
if you want to get text from specified element use .text() like $(".title").text() //will return Accountant.
You mean selecting them with a jQuery selector? That would be done like so:
$('.class1').attr('href') //class1 href, i persume you dont mean classA as it doesnt exist in your code
$('.class1').text(); //PersonA text using the same selector
$('.title').text(); //Accountant from the .title dd
Hello I have some HTML that looks like this,
<div id="music_interests">
<ul class="interests">
<li >
<div class="interest inline">
<img src=""/>
<div class="interest_popup">
1 users have this interest.
Remove interest </div>
</div>
</li>
</ul>
When users clicks the remove button I need to select the parent div (in this case music_interests). How would I go about that?
I have tried doing the following,
$(this).parent().parent().parent().parent() but is there a more elegant way?
To complicate things futher I will not actually no the parents ID when in the app as the remove button occurs in 4 or 5 different areas on the page.
you should use closest()
$(this).closest('div#music_interests');
//find the nearest div with id "music_interests"
//if i omitted the id, it retrieves the div with class "interest_popup"
or parents()
$(this).parents('div:eq(1)');
//get ALL the ancestor divs (until it reaches root tag)
//since music_interests is just 2 levels up, use :eq(1)
If the ID of the DIV you want to remove is static you should only use the ID selector (not something like $("div#music_interests")) as the ID selector is directly mapped to the DOM function document.getElementsById which is pretty fast:
$("#music_interests").remove();
If the ID isn't static you could get the UL just like that:
$(function(){ //execute when page has been loaded
$(".remove").click(function(){ //attach click handler
var removeDiv = $(this).closest("ul").parent().remove(); //get next UL -> DIV is its parent
return false; //stop further processing of "click" event
});
});
if remove button always exist in ul tag (in all your 4 or 5 different areas) then you can use the following code.
$(this).closest("ul").parent()
in this case u don't even need to give id to DIV tags
I have a blob of HTML that I'm retrieving using simple jQuery selectors, something like the following:
<div id="stuff">
<ul>
<li>some</li>
<li class="ninja">stuff</li>
</ul>
</div>
I'm basically doing:
var myblock = $("#stuff").html();
now I want to inject an additional li element to the bottom of that li list with very similar attributes to the li above it, but i want to change the class ninja to class samurai.
What's the best way of going about that with jQuery?
Simply select the <ul> and append the <li> to it
$("#stuff ul").append('<li class="samurai">stuff</li>');
If you actually wanted to copy the last <li> element, change the class then add to the list, then you could do something like this
var ul = $("#stuff ul");
ul.append(ul.find('li:last').clone().removeClass().addClass("samurai"));
pass true into clone() if you also want to copy event handlers too.
The problem with taking a whole chunk of HTML, changing an element and then reinserting is that any event handlers set up on elements that will be replaced when you reinsert the HTML will be lost, so it's more elegant/ and less cumbersome/intrusive to simply manipulate the part of the DOM that you need to.