Suppose I have two p tags in the document. I want to call two different effects using jQuery when onMouseOver event happens. Is it necessary that these two p tags be given Ids. Can't it be achieved without giving Ids to these tags ?
You don't have to give anything an id, however it is the best way to uniquely identify an element.
You can instead idenfity by class:
$(".myClass")
By attribute:
$("[src='image.jpg']")
By position in parent:
$("p:eq(2)")
A full list of selectors is available in the documentation
$('p:first'); // first p tag
$('p:last'); // last p tag
$('p').eq(1); // exactly the second p tag
There are several ways to select an element / elements:
$('.classname')
$('#id')
$('tagname')
$('[attr="value"]')
etc
although jQuery allows you to write faster and easier scripts, but unfortunately it makes you never understand the real JavaScript.
$("*") //selects all elements.
$(":animated") //selects all elements that are currently animated.
$(":button") //selects all button elements and input elements with type="button".
$(":odd") //selects even elements.
$(":odd") //selects odd elements.$("p") selects all <p> elements.
$("p.intro") //selects all <p> elements with class="intro".
$("p#intro") //selects the first <p> elements with id="intro".
$(this) //Current HTML element
$("p#intro:first") //The first <p> element with id="intro"
$("p:eq(2)") // The third <p> element in the DOM
$(".intro") //All elements with class="intro"
$("#intro") //The first element with id="intro"
$("ul li:first") //The first <li> element of the first <ul>
$("ul li:first-child") //The first <li> element of every <ul>
$("[href]") //All elements with an href attribute
$("[href$='.jpg']") //All elements with an href attribute that ends with ".jpg"
$("[href='#']") //All elements with an href value equal to "#"
$("[href!='#']") //All elements with an href value NOT equal to "#"
$("div#intro .head") //All elements with class="head" inside a <div> element with id="intro"
jQuery – Select element cheat sheet
Related
I have an HTML like this
<div class="this">
EXP
</div>
I want to add id to <a>. But do not know what to do.
First select your element using something like .getElementsByClassName(). Keep in mind that .getElementsByClassName() returns a NodeList collection of elements, so you'll want to access the first index (or loop over them). You can then simply set the ID with .id, as the ID is merely a property of an element.
This can be seen in the following:
const element = document.getElementsByClassName('this')[0];
element.id = 'element';
console.log(element);
<div class="this">
EXP
</div>
If you want to add this with Javascript, you'll need to use a selector to target your <a> tag and then set the id attribute on it. You can do this by using the querySelector() function or as seen below:
// Find an <a> tag that occurs below a class called "this" and set its id attribute
document.querySelector('.this > a').id = "some-id";
There are many other available functions to handle this through native Javascript and other frameworks, so your milage may vary depending on what you are using.
Example
In this example, we have provided some CSS that should only apply to an element with an id of "test" and we'll run the necessary code to show that the id is being added to the element (as it will be red):
document.querySelector('.this > a').id = 'test';
#test { color: red; }
<div class="this">
EXP
</div>
Add the id attribute to the <a> tag. See the differences of the middle line:
<div class="this">
<a id="expid" href="exp.com">EXP</a>
</div>
I have prepended one div inside some div with many others:
<div class="content">
<div>sss</div>
<div>aaa</div>
<div>bbb</div>
</div>
I added <div>ddd</div> before sss with:
$('.content').prepend('<div></div>');
And when I want to append some new element to new prepended div it add's it as text:
$('.content>div')[0].append('<p>ddd</p>');
If I remove [0] it works but it appends to all divs, I need that [0] to find first div.
To get the first element (that is still a jquery object) you can use .first():
$('.content>div').first().append($('<p>ddd</p>'));
Note that I also wrapped the <p> with $(...) to make it a valid html element (and not text).
I had a situation in which I wanted to focus either an input tag, if it existed, or it's container if it didn't. So I thought of an intelligent way of doing it:
document.querySelector('.container input, .container').focus();
Funny, though, querySelector always returns the .container element.
I started to investigate and came out that, no matter the order in which the different selectors are put, querySelector always returns the same element.
For example:
var elem1 = document.querySelector('p, div, pre');
var elem2 = document.querySelector('pre, div, p');
elem1 === elem2; // true
elem1.tagName; // "P".
My question is: What are the "reasons" of this behavior and what "rules" (if any) make P elements have priority over DIV and PRE elements.
Note: In the situation mentioned above, I came out with a less-elegant but functional solution:
(document.querySelector('.container input') ||
document.querySelector('.container') ).focus();
document.querySelector returns only the first element matched, starting from the first element in the markup. As written on MDN:
Returns the first element within the document (using depth-first
pre-order traversal of the document's nodes|by first element in
document markup and iterating through sequential nodes by order of
amount of child nodes) that matches the specified group of selectors.
If you want all elements to match the query, use document.querySelectorAll (docs), i.e. document.querySelectorAll('pre, div, p'). This returns an array of the matched elements.
The official document says that,
Returns the first element within the document (using depth-first pre-order traversal of the document's nodes|by first element in document markup and iterating through sequential nodes by order of amount of child nodes) that matches the specified group of selectors.
So that means, in your first case .container is the parent element so that it would be matched first and returned. And in your second case, the paragraph should be the first element in the document while comparing with the other pre and div. So it was returned.
That's precisely the intended behavior of .querySelector() — it finds all the elements in the document that match your query, and then returns the first one.
That's not "the first one you listed", it's "the first one in the document".
This works, essentially, like a CSS selector. The selectors p, div, pre and pre, div, p are identical; they both match three different types of element. So the reason elem1.tagName == 'P' is simply that you have a <p> on the page before any <pre> or <div> tags.
You can try selecting all elements with document.querySelectorAll("p.a, p.b") as shown in the example below and using a loop to focus on all elements that are found.
<html>
<body>
<p class="a">element 1</p>
<p class="b">element 2</p>
<script>
var list=document.querySelectorAll("p.a, p.b");
for (let i = 0; i < list.length; i++) {
list[i].style.backgroundColor = "red";
}
</script>
</body>
</html>
I have the following markup
<div class = "general">
<div id ="custom"></div>
</div>
How to change id = "custom" in all <div> with class="general" from href on page using jQuery?
You can try this:
$("div.general").each(function() {
$(this).children("div#custom").text($(this).children("a").attr("href"));
});
If I understand you correctly, you want to iterate through all div.generals, and change the text of each child div#custom to the href of the child a.
See a working example on JSfiddle.
Also, another tip is to avoid using multiple elements with the same id. In your code you have a <div> with id="custom". You also say that the div.general appears multiple times — therefore, the id "custom" will appear multiple times. This is bad practice. I suggest that you change id to class.
You need to loop through all div.general and replace the id attribute of div#custom to whatever is there as the anchors href property. The following code will work:
$(".general").each(function(){
$(this).find("#custom").attr("id", $(this).find("a").attr("href").replace("#", ""));
})
Here the .find() will dig out elements from any depth inside the parent. If you are sure about the DOM position of the elements, you can change the .find() to .children()
Well I'm trying to write a validation jQuery plugin, but for that I need to find all inputs inside of a container, which is marked with an attribute. However, that container may have other sub-containers, also marked with attributes, and they may have their own inputs.
I need to select all inputs, descendants of the parent container (accessed by $(this)) which are not descendants of the sub-containers. Is that possible?
Some code to illustrate:
<div data-container>
<input>
<div class="form-group">
<input>
</div>
<input>
<div data-container>
<input>
<input>
<input>
</div>
</div>
I want to select those first three inputs, and ignore the ones inside the children data-container. The one inside the form-group must be selected too.
Use .not() to exclude a selection from an existing jQuery selection:
var yourSelection = $(this).find('input').not($(this).find('[data-container] input'));
JSFiddle (I replaced the $(this) by $('[data-container]:first') in the fiddle for simplicity)
This should work, here http://jsfiddle.net/2Wv7P/
$('div[data-container] input:lt(3)')
You can select based on the parent div like this. Only the first level children are going to be selected based on you given tag, assuming you ID the parent div as #parent
$('#parent > input')
So following this path, if you have to select the parent with $(this), which is to say using 'this', then you can select this same set of 'input's using
$('#' + this.id + ' > input')
For example
see this fiddle