Understand JQuery Selector expression - javascript

I am trying to read some JavaScript that is selecting element(s) using this expression
$("body > div:not(.layout-ignore):not(.ui-loader)")
I get that its starting at the body but is that the Greater Than (>) symbol saying select all div elements within the body element that do not have .layout-ignore and also not .ui-loader class attributes?
Can anyone explain to me this syntax? Also point me to some online documentation that helps me further understand this selector expression.
Cheers

jQuery uses CSS selectors as its basis. The MDN has an extremely thorough guide as to what these are and how they work.
Please see here: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_started/Selectors
and here: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started
In your example it means any div (that is not of class .layout-ignore or .ui-loader) that is a child of body. Meaning nested divs would not be selected.
Hope this helps.

...is that the Greater Than (>) symbol saying select all div elements within the body element that do not have .layout-ignore and also not .ui-loader class attributes?
The > is saying that the div that matches must be an immediate child of body. It's called a "child combinator". So the only div elements that can possibly match are immediate children of body, they can't be inside another intermediate element. So:
<body>
<div><!-- This div matches the selector -->
<div><!-- But this div does not --></div>
</div>
</body>
The two :not qualifiers (which are the "negation pseudoclass") are saying that the div cannot have the class layout-ignore and cannot have the class ui-loader.
So in total:
<body>
<div><!-- This div matches the selector --></div>
<div><!-- But this div does not, it's not a direct child of body --></div>
</div>
<div class="layout-ignore"><!-- This does not because it has layout-ignore --></div>
<div class="ui-loader"><!-- And neither does this, because it has ui-loader --></div>
</body>

The body > div code is select all div that are direct children of body (http://devdocs.io/css/child_selectors)
<body>
<div>first</div>
<span>
<div>second</div>
</span>
</body>
(ignore that the html markup isn't valid here) but with that selector it will only select the div with the text first.
the :not selector will exclude everything within it: http://api.jquery.com/not-selector/
<body>
<div>first</div>
<span>
<div>second</div>
</span>
<div class="example"></div>
</body>
body>div:not(.example) with the body>div it will select both the "first" div and the .example but will exclude .example div from the collection.

Related

Why is a <div> tag or <form> tag written as a child to a <p> tag in an HTML code rendered by Chrome as not a child, but a sibling of the <p> tag? [duplicate]

As far as I know, this is right:
<div>
<p>some words</p>
</div>
But this is wrong:
<p>
<div>some words</div>
</p>
The first one can pass the W3C validator (XHTML 1.0), but the second can't. I know that nobody will write code like the second one. I just want know why.
And what about other tags' containment relationship?
An authoritative place to look for allowed containment relations is the HTML spec. See, for example, http://www.w3.org/TR/html4/sgml/dtd.html. It specifies which elements are block elements and which are inline. For those lists, search for the section marked "HTML content models".
For the P element, it specifies the following, which indicates that P elements are only allowed to contain inline elements.
<!ELEMENT P - O (%inline;)* -- paragraph -->
This is consistent with http://www.w3.org/TR/html401/struct/text.html#h-9.3.1, which says that the P element "cannot contain block-level elements (including P itself)."
In short, it is impossible to place a <div> element inside a <p> in the DOM because the opening <div> tag will automatically close the <p> element.
According to HTML5, the content model of div elements is flow content
Most elements that are used in the body of documents and applications are categorized as flow content.
That includes p elements, which can only be used where flow content is expected.
Therefore, div elements can contain p elements.
However, the content model of p elements is Phrasing content
Phrasing content is the text of the document, as well as elements that
mark up that text at the intra-paragraph level. Runs of phrasing
content form paragraphs.
That doesn't include div elements, which can only be used where flow content is expected.
Therefore, p elements can't contain div elements.
Since the end tag of p elements can be omitted when the p element is immediately followed by a div element (among others), the following
<p>
<div>some words</div>
</p>
is parsed as
<p></p>
<div>some words</div>
</p>
and the last </p> is an error.
Look at this example from the HTML spec
<!-- Example of data from the client database: -->
<!-- Name: Stephane Boyera, Tel: (212) 555-1212, Email: sb#foo.org -->
<DIV id="client-boyera" class="client">
<P><SPAN class="client-title">Client information:</SPAN>
<TABLE class="client-data">
<TR><TH>Last name:<TD>Boyera</TR>
<TR><TH>First name:<TD>Stephane</TR>
<TR><TH>Tel:<TD>(212) 555-1212</TR>
<TR><TH>Email:<TD>sb#foo.org</TR>
</TABLE>
</DIV>
Did you notice something? : There was no closing tag of the <p> element. a mistake in the specs ? No.
Tip #1: The closing tag of <p> is OPTIONAL
You may ask: But then how would a <p> element knows where to stop?
From w3docs:
If the closing tag is omitted, it is considered that the end of the paragraph matches with the start of the next block-level element.
In simple words: a <div> is a block element and its opening tag will cause the parent <p> to be closed, thus <div> can never be nested inside <p>.
BUT what about the inverse situation ? you may ask
well ...
Tip #2: The closing tag of the <div> element is REQUIRED
According to O’Reilly HTML and XHTML Pocket Reference, Fourth Edition (page 50)
<div> . . . </div>
Start/End Tags
Required/Required
That is, the <div> element's end will only be determined by its closing tag </div> hence a <p> element inside is will NOT break it.
After the X HTML, the conventions has been changed, and now it's a mixture of conventions of XML and HTML, so that is why the second approach is wrong and the W3C validator accepts the things correct that are according to the standards and conventions.
Because the div tag has higher precedence than the p tag. The p tag represents a paragraph tag whereas the div tag represents a document tag.
You can write many paragraphs in a document tag, but you can't write a document in a paragraph. The same as a DOC file.

removing element closest jquery

I want to remove/hide the element inside the parent in specific range. Is that possible in jquery?
<body class="page page-id-5269 page-parent page-template-default logged-in kleo-navbar-fixed navbar-resize js" itemtype="http://schema.org/WebPage" itemscope="">
<p>Your account is not setup as a vendor.</p>
<form action="" method="POST">
//....
</form>
<br class="clear" style="display: none;">
//other element here that should be display ...
</body>
on the code above i want to remove element inside the body tags but until in <br class="clear"> only. The element that i want to remove is dynamically generated it can be div, p, span, etc...
Currently i have code like this but it will remove only the specific element (not dynamicaly):
$('body.page div').first().hide();
Please help. Thank you!
That is you want to hide all the previous siblings of br.clear element which is a child of body.page so
$('body.page > br.clear:first').prevAll().hide();
This might be solution:
$('body.page').find('*').each(function(){ //iterating all children
$(this).hide();// removing elment
if($(this).is( "br.clear" ))//checking element is br having class clear
return false;// breaking loop
});
See DEMO: Instead of using body i have used div.container.

How to select certain class in jQuery

Here's the problem; I have a couple of divs like the one below, same class name, no id. I need to modify the <span> text below the <h4> tag, based on where's the mouse cursor on those 3 images. I do this using javascript, by using mouseenter() method. The problem is that the method changes every span text from whole web page, not only from the class with class name "parent" where the mouse cursor is at the moment.
<div class="parent">
<div class="parent.child">
<div class="parent.chil.child">
<div class="parent.chil.child.child">
<img src ="link1" data-price="a">
<img src ="link2" data-price="b">
<img src ="link3" data-price="c">
</div>
</div>
</div>
<h4>
text
</h4>
<p><span class = "spanClassName">text to be changed</span>some text</p>
<div class=child1"></div>
</div>
How do I select only the link where's the mouse, from the curent "parent" div, even if there are several div with same class name, "parent".
I hope I was understood, if not, please ask and I try to explain more.
You can use .closest() to find parent with .parent class
$('.parent\\.chil\\.child\\.child img').on('hover', function(){
$(this).closest('.parent').find('.spanClassName').text($(this).attr('data-price'))
});
DEMO
Additionally as per documents you need to escape . in your selectors
To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?#[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\. For example, an element with id="foo.bar", can use the selector $("#foo\\.bar").
If you already know the specific parent node, just use parent.find('.spanClassName'). If you don't have the parent node, but you know which link the mouse is on, you can use link.closest('.parent').find('.spanClassName').

JS Only apply if condition to relevant item

I have a small group of items as shown below.
<div class="item">
<div class="date">2013-08-08</div>
<div class="headline"><a data="normal" href="#">Title</a></div>
</div>
<div class="item">
<div class="date">2013-10-08</div>
<div class="headline"><a data="special" href="#">Title</a></div>
</div>
If the title has a data attribute of special, I want to make the date bold for that item only.
I have the below code to try and do this.
<script>
if ($(".headline a [data='special']")){
$( ".date" ).wrap( "<b></b>" );
}
</script>
However this makes all items bold if the condition is true.
I am familiar with using this in JS but not sure how to relate it to another div above.
What is the best way to do this?
I am happy to change the html structure if required as well.
Try the following:
$(".headline a[data='special']").parent().siblings(".date").wrap("<b></b>");
The parent() function will select the div.headline for a matching <a> tag; then, siblings(".date") will select children of the parent of div.headline (which are called siblings) that have the date class.
It sounds like you'd like to select the .date element in .item elements which contain .headline a[data="special"] elements.
$('.item:has(.headline a[data="special"]) .date')
will select the correct .date elements for my given assumptions, you can then call .wrap('<b></b>').
Also note: [data] is not a valid [data-*] attribute. You must have a hyphen and a name for custom data attributes.

javascript/jquery select all child elements inside a parent element

I have a bunch of child elements that are uniquely identified within a parent div. I want to know if there's a way in jQuery (or javascript) to capture all of them? The number of children in the parent div is arbitrary, meaning it could be any number for each div. For example:
<div class="parent1">
<span class="child1">some text here</span>
<span class="child2">some other text</span>
...
<span class="child49">yet more text</span>
<span class="something_else">other text i don't want to select</span>
</div>
<div class="parent2">
<span class="child1">some text</span>
<span class="child2">some text</span>
...
<span class="child120">some text</span>
</div>
So considering the above example, how do I get ALL the children (.child1 through .child49) within the class parent1?
I know that doing the following will work in jQuery (using multiple selector):
$(".child1, .child2, ..., .child49").css("background","red");
But is there a better way? I won't always know how many children are in each parent.
EDIT: also, I might have other children in the parent with a different class name that I DO NOT want to select; I specifically want to select all the "child*" classes.
$('.parent1 span[class^="child"]')
will select all the spans that start with the class child under the class .parent1.
If you want all the span.childX under all parentX then use:
$('div[class^="parent"] span[class^="child"]')
This is using a CSS3 attribute selector which jQuery have implemented (and extended in some cases). From the documentation:
E[foo^="bar"] an E element whose "foo" attribute value begins exactly with the string "bar"
These codes gets all child in div.parent1 and div.parent2
$('[class^="parent"] span').css({ });
$('[class^="parent"]').children().css({ });
Thess codes gets onli the children for parent 1
$('.parent1 span').css...
$('.parent1').children().css...
use .children along with .filter, if number of children are not certain then label all childs which you want to manipulate of parent1 as child1
$(".parent1").children().filter(".child1").css({color:'Red'});
here is the fiddle http://jsfiddle.net/8hUqV/1/
jquery children

Categories

Resources