Having issue with DOM selection in jquery - javascript

<div class="wrapper">
<p class="text"></p>
</div>
<div class="wrapper">
<p class="text"></p>
<img></img>
</div>
<div class="wrapper">
<p class="text"></p>
<div class="vid"></div>
</div>
Assume above is a list of users' post, and I want to identify type of post of them. To select the image or video type is easy, for example the video, just select like $('.wrapper .vid').
But there is a problem when I want to select plaintext type of post, because the class text also appear in vid and image type of post.

Looks like you want wrapper elements which does not hae vid or img then
$('.wrapper').not(':has(img, .vid)')
If you want the text elements within them
$('.wrapper').not(':has(img, .vid)').find('.text')

You can use filter to get the three different types of posts. Something like this:
var $textPosts = $('.wrapper').filter(function() {
return $(this).find('img, .vid').length == 0;
});
var $imgPosts = $('.wrapper').filter(function() {
return $(this).find('img').length > 0;
});
var $vidPosts = $('.wrapper').filter(function() {
return $(this).find('.vid').length > 0;
});
Also note that the img HTML tag is self closing, eg:
<img src="foo.jpg" title="Foo" />

If i get this right that you want to get all the test in <p> with the class text, then you can do something like this
$('.wrapper > .text').html()
The above code will give you the content of only those element with class "text" that are direct under class "wrapper"

You can use .filter() to filter out the element with class text whose has no sibling:
var text = $('.text').filter(function() {
return $(this).siblings('*').length == 0
}).text();
Fiddle Demo

You can use
$('.wrapper p.text').text()
fiddle demo

Related

Select span of sibling div jquery

I am using jQuery selectors, and I need to be able to find each span individually that contains a dollar amount. For example, I'd like to find & change the first span to $15 and the third span to $40. I have put in class names in my example, but in my problem I do not know the class names, and I do not know which span the 2nd dollar amount is in. There also could be more or less div's and spans.
This happens to be in a form, and I find the first dollar amount like this:
$("form[action='/cart'] span:contains('$'):first).replaceWith("$15");
I have the following HTML.
<div class="daddy">
<div class="kid1">
<span>$10</span>
</div>
<div class="kid2">
<span>Nothing to see here</span>
</div>
<div class="kid3">
<span>$20</span>
</div>
</div>
Thanks
You can iterate over each span element and check if it's innerHTML contains $ symbol. If so, return all these spans and their position (index).
Once you have their index position, you can modify them as you like.
Note: No jQuery needed in this solution.
Example: You can push every index of each matched span to an array. In this particular case, it would look like var matchedIndexes = [0, 2]. Then basically, if you want to change e.g. the first element - simply use matchedIndexes[0].
var elems = document.getElementsByTagName('span'),
matchedIndexes = [];
Array.from(elems).forEach(function(v,i){
if (/\$/.test(v.innerHTML)){
matchedIndexes.push(i);
}
});
//change html of the first element
elems[matchedIndexes[0]].innerHTML = '$15';
//or change the last matched element
elems[matchedIndexes[matchedIndexes.length-1]].innerHTML = '$99';
<div class="daddy">
<div class="kid1">
<span>$10</span>
</div>
<div class="kid2">
<span>Nothing to see here</span>
</div>
<div class="kid3">
<span>$20</span>
</div>
</div>
why not having an array with values to be updated and query the span which contains '$' and update accordingly?
var ratesToUpdate = [15, 40, 70];
var spans = $("form[action='/cart'] span:contains('$')");
spans.each(function(index, span){
$(span).text('$'+ratesToUpdate[index]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form action="/cart">
<div class="daddy">
<div class="kid1">
<span>$10</span>
</div>
<div class="kid2">
<span>Nothing to see here</span>
</div>
<div class="kid3">
<span>$20</span>
</div>
<div class="kid4">
<span>nothing</span>
</div>
<div class="kid5">
<span>nothing</span>
</div>
<div class="kid5">
<span>$50</span>
</div>
</div>
</form>
I like the answer Kind user gave - but here is my stab at it. I couldn't make it more dynamic as the addition values are not similar (first one is added by 5, third is doubled...)
JSFiddle Here: https://jsfiddle.net/rL36jv8m/
Your HTML
<div class="daddy">
<div class="kid1">
<span>$10</span>
</div>
<div class="kid2">
<span>Nothing to see here</span>
</div>
<div class="kid3">
<span>$20</span>
</div>
</div>
Array of addition values to corresponding divs.
var addValues = [
5,
'',
20
]
Iteration:
$('.daddy').children().each(function(i, o) {
var elem = $(o).find('span');
if (elem.html().indexOf('$') === 0) {
elem.html('$' + (parseInt(elem.html().replace('$', '')) + addValues[i]))
}
})
Hope this helps.
Would this solve your problem?
var values = [15, 40];
$("form[action='/cart'] span:contains('$')").each(
function(index, element)
{
element.value = '$'+ values[index];
});

AppendChild a element above a cerain element

So i have a div element which will be filled dynamically with others divs using the appendChild Method, this should display a list. The User is now able to sort that list with the JqueryUI Sortable option.I also added some sortable option attribues like follows:
Options:
$("#NameContainer").sortable("option", "axis", "y");
$("#NameContainer").sortable( "option", "containment", "parent" );
LIST
<div id="NameContainer" class="ui-widget">
<div id="Name_1">John</div>
<div id="Name_2">Jack</div>
<div id="Name_3">Charlie</div>
<div id="Name_4">Sawyer</div>
<div id="Name_5">Yin</div>
<div id="Name_6">Ben</div>
</div>
Now comes my problem. The appendChild always inserts the new div at the bottom of the container but i want to to add some space at the bottom of to the Container Div with a "br" or something like that. I want to add that space to make sure that when the user sorts the last item of that list it will get sorted correctly because the "containment" bounds sometimes wont allow to sort under the last item.
<div id="NameContainer" class="ui-widget">
<div id="Name_1">John</div>
<div id="Name_2">Jack</div>
<div id="Name_3">Charlie</div>
<div id="Name_4">Sawyer</div>
<div id="Name_5">Yin</div>
<div id="Name_6">Ben</div>
<br><!--SPACEHOLDER-->
</div>
So here comes my Question is there away to appendChild above a certain element? Like a "br" "div" or "p"?
Try this instead of appendChild:
Please note I have used random value to add in div as I don't have your dynamic value.
check fiddle: https://jsfiddle.net/dqx9nbcy/
<div id="NameContainer" class="ui-widget">
<div id="divspacer"></div>
</div>
<button id="btn">ADD Element</button>
$(document).ready(function(){
$("#btn").click(function(){
var parentnode = document.getElementById("NameContainer");
var existnode = document.getElementById("divspacer");
var rand = Math.floor((Math.random() * 10) + 1);
var newName = document.createElement("div");
newName.setAttribute("id", rand);
newName.setAttribute("value", rand);
newName.setAttribute("class","ui-widget-content");
newName.innerHTML = rand;
parentnode.insertBefore(newName,existnode);
});
});
refer http://api.jquery.com/appendto/ but you need to make sure that your are targeting right tag.
You can try with this code snippet.
HTML Snippet
<div id="NameContainer" class="ui-widget">
<div id="Name1">Name1</div>
<div id="Name2">Name2</div>
<div id="Name3">Name3</div>
<div id="Name4">Name4</div>
<br>
<br>
</div>
Javascript Snippet
$(document).ready(function(){
$("#btn").click(function(){
var containerDiv= $("#NameContainer");
var childList = containerDiv.children("div");
var newElementid = childList.length;
var newName = document.createElement("div");
newName.setAttribute("id", "Name"+(newElementid+1));
newName.setAttribute("value", "Name"+(newElementid+1));
newName.setAttribute("class","ui-widget-content");
newName.innerHTML = "Name"+(newElementid+1);
$(childList[childList.length-1]).after(newName);
});
});
This is specific to a situation where there are some elements in the initial list. The same can be modified for dynamic list of implementation by validating that childList.length is != 0 before using the same.

Add class with a particular div

I have this div
<div class="newDiv">
It is generating in loop, something like
<div class="newDiv">
<div class = "innerDiv">
SomeCode
</div>
</div>
<div class="newDiv">
<div class = "innerDiv">
SomeCode
</div>
</div>
<div class="newDiv">
<div class = "innerDiv">
SomeCode
</div>
</div>
Now I want to add another class "BrightDiv" with the div that generated at odd places like
with first and third div.
what should I do to add Class "BrightDiv" along with "newDiv" with every div at odd place?
Try this : You can use :odd or :even to select odd / even elements, but it is depend on the index position and not natural number count. So In your case, you want first and third position div i.e. with index= 0 and 2 which is even by index position and hence use :even.
$('div.newDiv:even').addClass('BrightDiv');
DEMO
You can use filter to select only the odd indexed divs
$(".newDiv").filter(function() {
return $(this).index() % 2 == 1;
}).addClass("BrightDiv");
this will give you a solution $("div:even").addClass("BrightDiv");
Ways to achieve this:
CSS:
.newDiv:nth-child(odd) { /*CSS*/ }
or
.newDiv:nth-child(2n-1) { /*CSS*/ }
jQuery:
$('.newDiv:odd').addClass('BrightDiv');

JQuery : Remove class, not child content

I use jQuery to append the content into each contentx class like.
<div id="sidebar">
<div class="contentx"></div>
<div class="contentx"></div>
</div>
<script>
$("#sidebar .contentx").each(function()
{
//Append here
}
</script>
After Append I have, for example :
<div id="sidebar">
<div class="contentx">
something 1 is inserted here.
</div>
<div class="contentx">
something 2 is inserted here.
</div>
</div>
but I want to remove class="contentx" whenever the content is appended. This mean I have only :
<div id="sidebar">
something 1 is inserted here.
something 2 is inserted here.
</div>
How
Option 1
If you just want to remove the class "contentX" from the div after the content has been added, you can try the following:
$('#sidebar .contextX').each(function () {
// Append here.
}).removeClass('contextX');
EDIT: Seems I misread the question a little (based on your indicated desired output).
Option 2
If you want to remove the entire element and replace it with the content of your choice? For that, you can try:
$('#sidebar .contextX').each(function () {
$(this).replaceWith('<new content here.>');
});
jQuery replaceWith
Besides the append, call removeClass
$("#sidebar .contentx").each(function()
{
//Append here
$(this).removeClass('contentx');
}
Try this
var tmp = $(".contentx").html();
$('.contentx').append(tmp);
var tmp2 = $(".contentx").html();
$('.contentx').remove();
$('#sidebar').append(tmp2);

Javascript onmouseover and onmouseout

You can see in the headline what it is. I've four "div", and therein are each a p tag. When I go with the mouse on the first div, changes the "opacity" of the p tag of the first div. The problem is when I go on with the mouse on the second or third "div" only changes the tag "p" from the first "div". It should changes the their own "p" tags.
And it is important, that i cannot use CSS ":hover".
The problem is clear, it is that all have the same "id".
I need a javascript which does not individually enumerated all the different classes.
I' sorry for my english.
I hope you understand me.
My script:
<div onmouseout="normal();" onmouseover="hover();" >
<p id="something">LOLOL</p>
</div>
<div onmouseout="normal();" onmouseover="hover();" >
<p id="something">LOLOL</p>
</div>
<div onmouseout="normal();" onmouseover="hover();" >
<p id="something">LOLOL</p>
</div>
<div onmouseout="normal();" onmouseover="hover();" >
<p id="something">LOLOL</p>
</div>
Javascript:
function normal() {
var something = document.getElementById('something');
something.style.opacity = "0.5";
}
function hover() {
var something = document.getElementById('something');
something.style.opacity = "1";
CSS:
p {
opacity: 0.5;
color: red;
}
As Paul S. suggests, you need to pass this to the function so that it knows which element it has to work on.
<div onmouseout="normal(this);" onmouseover="hover(this);" >
<p>LOLOL</p>
</div>
<div onmouseout="normal(this);" onmouseover="hover(this);" >
<p>LOLOL</p>
</div>
<div onmouseout="normal(this);" onmouseover="hover(this);" >
<p>LOLOL</p>
</div>
<div onmouseout="normal(this);" onmouseover="hover(this);" >
<p>LOLOL</p>
</div>
And then select the child element <p> for the passed <div>. Here I select the first child p, i.e. the first element in the array of children of this element with tag p, that's why you see [0]. So if in each div you had two paragraph, then you could use e.g. getElementsByTagName("p")[1] to select the second <p>.
function normal(mydiv) {
mydiv.getElementsByTagName("p")[0].style.opacity="0.5";
}
function hover(mydiv) {
mydiv.getElementsByTagName("p")[0].style.opacity="1";
}
See the working example here: http://jsfiddle.net/mastazi/2REe5/
Your html should be something like this:
<div onmouseout="normal(1);" onmouseover="hover(1);">
<p id="something-1">LOLOL</p>
</div>
<div onmouseout="normal(2);" onmouseover="hover(2);">
<p id="something-2">LOLOL</p>
</div>
<div onmouseout="normal(3);" onmouseover="hover(3);">
<p id="something-3">LOLOL</p>
</div>
<div onmouseout="normal(4);" onmouseover="hover(4);">
<p id="something-4">LOLOL</p>
</div>
As you can see, we have different ids for your elements, and we pass the ids through the function that we trigger with onlouseover and onmouseout.
For your javascript, your code could be something like this:
function normal(id) {
var something = document.getElementById('something-'+id);
something.style.opacity = "0.5";
}
function hover(id) {
var something = document.getElementById('something-'+id);
something.style.opacity = "1";
}
For normal() and hover() we receive an id and change the style for the current element that have this id.
Please, check this JSFiddle that I've built for you.

Categories

Resources