target img class name - javascript

I know I can write:
$('.2020').css("padding", "20px");
But how do I write it like:
$('.a').children('img').children('.2020').css("padding", "20px");
<div class"a">
<img class="2020" src="img/swatch/2020.jpg" >
<img class="2021" src="img/swatch/2021.jpg" >
<img class="2022" src="img/swatch/2022.jpg" >
</div>
http://jsfiddle.net/ssRYk/

Your selector $('.a').children('img').children('.2020') tries to find elements with class 2020 which is inside an img element which is inside an element with class a.
Ex
<div class="a">
<img src="img/swatch/2020.jpg" >
<span class="2020"></span>
</img>
</div>
But in your case the img element has the class attribute, so you have two choices either concatenate the img and .2020 selector like .children('img.2020') or find the img elements using .children('img') and filter elements with class within that set using .filter('.2020')
If you want to retain the same structure, then you can
$('.a').children('img').filter('.2021').css("padding", "5px");
Demo: Fiddle

Your fiddle and code above both have an error, it is missing the = in your class="a"
You are saying look for all elements that have the class a. Than look for children that are images. Now look for images that have a child with the class 2021. Since images can not have children, that code would never return anything.
You can combine the two children statements with one selector instead of doing multiple actions.
$('.a').children('img.2021').css("padding", "5px");
You could also write it without the children in just one selector
$('.a > img.2021').css("padding", "5px");
The alternative is filtering.

Related

How add ID to HTML href with javascript

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>

Append an element inside a specific div's element using Javascript

I know how to append an element inside another element, but how do I specify which class I want to append it to?
For example:
<div class="main" id="11">
<div class="somethingelse>
<div class="moreThings">
/*How to append to this class?*/
</div>
<div class="extraThings">
</div>
</div>
</div>
What I have is something like this:
var x = document.createElement("IMG");
x.setAttribute("src", "../truck.png");
document.getElementById(order_id).appendChild(x);
document.getElementById("btn_transport_"+order_id).style.display = "none";
There could be hundreds of classes with same name which is why I need to define them by id.
At the moment I am appending the img under everything other divs, but I would like to append it inside "morethings". How would I do that?
You could do something like this:
document.getElementById(order_id).getElementsByClassName("moreThings")[0].appendChild(x);
Make sure getElementsByClassName("moreThings") returns at least one element.
You can find out more about getElementsByClassName(...) from HERE. The gist of it is:
Returns an array-like object of all child elements which have all of the given class names
You could use document.querySelector. It allows CSS-like selectors. In your case it could look like
const myElementToAppendTo = document.querySelector('#myID .morethings');
myElementToAppendTo.appendChild(x);

How to recursively select all children under an element Javascript

I need a function that recursively selects all child elements but wont select elements (and those elements children) if they have the "foo" attribute.
<section>
<div>
<span foo>
<input>
</span>
</div>
<p>
<img>
</p>
</section>
//should return [section, div, p, img]
I need raw Javascript please
edit:
I tried something like this:
$tag.querySelectorAll(":not([foo])")
but querySelectorAll(":not([foo])") will still return the children of the unselected element.
You can use element.querySelectorAll() with the :not modifier here, together with the [attr] selector:
var nonFooElements = parentElement.querySelectorAll("*:not([foo])");
Be aware that this sort of call will be moderately expensive because the selector doesn't begin with an id or a classname, so don't do huge amounts of it.
I adapted this answer from this one: https://stackoverflow.com/a/21975970/5009210

How to hide a div that doesn't have an ID

I need to write a piece of code (I am thinking of JavaScript/jQuery) that would hide the two divs highlighted. The problem is that they do not have IDs and they belong to classes but are not the only objects in those classes. So I cannot hide the classes, because that will hide more things that I want. The "parent" div has an ID.
Please find the code here:
Is there any way I can reference the divs that I want to hide by the order number from the parent? Any other solution would be greatly appreciated.
As I see that those elements are sub child of an element with an id of #view so you can make use of nth- selectors or you can use jQuery :eq()
$("#view > div:nth-of-type(3) > div:nth-of-type(2),
#view > div:nth-of-type(4) > div:nth-of-type(1)").hide()
Or using CSS (Recommended)
#view > div:nth-of-type(3) > div:nth-of-type(2),
#view > div:nth-of-type(4) > div:nth-of-type(1) {
display: none;
}
Here, the first selector i.e #view > div:nth-of-type(3) > div:nth-of-type(2) selects a third div element which is a direct child to an element having an id of #view and further it selects a direct div element which is a second child of that type
Second selector i.e #view > div:nth-of-type(4) > div:nth-of-type(1) selects fourth direct div child element to an element having an id of #view and further, it selects first direct child div
This worked for me If there is no other sibling with same class name.
HTML
<div>
<div class="child"></div>
</div>
<div id="parent">
<div class="child">
</div>
</div>
<button onclick="hideDivs()">Hide</button>
Javascript
function hideDivs() {
var parentDiv = document.getElementById('parent');
var childDivs = parentDiv.getElementsByClassName('child');
for (var i = 0; i < childDivs.length; i++) {
childDivs[i].style.display = "none";
};
}
I am not a fan of coding by position (e.g. the 3rd or 4th element) because relatively minor changes to the markup such as just adding a new div for spacing can break code that relies on specific hard-coded positions.
If you want something that won't break when there are changes to the markup that might change the relative position of items, then you have to look for more specific content that you want to hide. There are many different ways to do this depending upon what you know about the content and what is the best marker to indicate that you have the right div.
Here's one way that looks for unique identifiers in the content you want to hide, then goes up to the proper parent to hide that content:
$("#RoleListTB").closet(".h1r1").hide();
$("#AccessProfileListTB").closest(".h111").hide();
You could use the table's ids to identify the container.
$("#RoleListTB").closest(".hlrl").hide();
closest() is looking up the DOM to the next matching parent, so you can start at your table as shown.
i've made a fiddle for this:
<a href="#" id="toggle" >show/hide</a>
<div>
<div class="hlrl">
<span id="RoleListTB">
RoleList Table
</span>
</div>
</div>
$("#toggle").click(function(){
$("#RoleListTB").closest(".hlrl").toggle();
});
http://jsfiddle.net/NGVQ3/
You could easily do this by using a CSS pseudo-selector in your query.
$('#view').find('div.h1r1:nth-of-type(2)')
or you could just be more specific
.h111+.h1r1
You can use :gt Jquery selector to search by index:
$( ".some:gt(0)" );
0 - is first .some
You can use the :eq selector to select an element at a particular index.
Assume the parent div has an id parent
it had child div's having the class sub.
so if you want to hide the second child element
$("#parent .sub:eq(1)").hide();
since the child ordering starts with `0' index
If you are sure that their positions are fixed and that won't change, then you could use nth-child selector.
Something like this:
$("#view").children("div:nth-child(3)").children("div:nth-child(2)").hide();
$("#view").children("div:nth-child(4)").children("div:nth-child(1)").hide();
Or, just:
$("#view > div:nth-child(3) > div:nth-child(2)").hide();
$("#view > div:nth-child(4) > div:nth-child(1)").hide();
Alternatively, using .eq:
$("#view").children("div").eq(2).children("div").eq(1).hide();
$("#view").children("div").eq(3).children("div").eq(0).hide();
Note: .eq is zero-based.
Divs can have more than one class . . .
<div class="h111">
changed to
<div class="h111 hideDiv">
CSS
.hideDiv {display: none;}
then use javascript to show it when you want it to be shown :)
Your div contains the tables which have a ID. So you can use
$('#yourTableIDHere').parent().hide();
This code will hide your div.

set image as a background of a sibling element

my goal is to let the user to choose the background, but my js doesn;t work.
<div class="step">
</div>
<div id="images">
<img src="" data-src="">
<img src="" data-src="">
<img src="" data-src="">
<img src="" data-src="">
</div>
<div class="step">
</div>
<div class="step">
</div>
The images div is dynamic and should always change the image of the .step just before.
here is my buggy js:
$(document).on('click', '#images img', function(){
var src = $(this).data('src');
$(this).before().find('.step').css("background" , "url("+src+")");
});
I think what you are selecting is wrong and before() appends elements.
$(this).parent().prev('.step').css("background" , "url("+src+")");
basic explanation
$(this) //the image
.parent() // the div #images
.prev('.step') //get the previous sibling with the class step
.css("background" , "url("+src+")");
If you want all of the .step elements, you would use .siblings(".step") instead of .prev(".step")
I think you want prev(), not before()
$(this).parent() will give you the div which holds the images & .prev('.step') gives you the previous element with class step. before() is only used to insert before each element in the set of matched elements.
$(this).parent().prev('.step').css("background" , "url("+src+")");
The .before() method inserts content, it doesn't find an earlier element. You want the .prev() method, noting that it finds the previous sibling so you need to traverse via the .parent():
$(this).parent().prev().css("background" , "url("+src+")");
Demo: http://jsfiddle.net/DBRkS/
Note that .prev() doesn't search backwards until it finds a matching element, it selects the immediately preceding sibling if it matches the selector you supply, otherwise it returns nothing. So for the html you've shown it would work the same with or without the ".step" selector.

Categories