I have a div with ID as "parentID" to the parent div and based on this, I am dynamically adding "ChildID" to all its child divs along with its "parentID".
jQuery(document).on('click', '.split-id', function() {
var parentID = jQuery('.parent').attr('id');
var childID = jQuery('.child').attr('id', jQuery(this).closest('.parent').attr('id') + 'ChildID');
jQuery('#displayParentID').html('Parent ID : ' + parentID);
jQuery('#displayParentChildID').html('Parent Child ID : ' + childID);
jQuery('#displayOnlyChildID').html('Child ID only : ' + childID);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="parent" id="parentID">
<div class="child"></div>
<div class="child"></div>
</div>
<div id="displayParentID"></div>
<div id="displayParentChildID"></div>
<div id="displayOnlyChildID"></div>
Split
How can I get all child element IDs without parent div IDs? like below onClicking of Split tag...
Parent ID : parentID
Parent Child ID : parentIDChildID
Child ID only : ChildID (This is what I am expecting)
Fiddle
Don't know what exactly is purpose of what you are asking, but you can replace your js code in your fiddle with this and it works as you expected.
* Mind that, when you use attr function to set a property it is returning Object, not only string label.
* If you will give multiple children the same id it will not work, because in html code ids need to be unique
jQuery(document).on('click', '.split-id', function () {
var parentID = jQuery('.parent').attr('id');
var childElement = jQuery('.child').attr('id', parentID + 'ChildID');
var childID = childElement.attr('id');
jQuery('#displayParentID').html('Parent ID : ' + parentID);
jQuery('#displayParentChildID').html('Parent Child ID : ' + childID);
jQuery('#displayOnlyChildID').html('Child ID only : ' + childID.replace(parentID, ''));
});
If you have some more questions, go on and ask.
Related
I have list element like this
<ol class="listItem">
<li id="#item-1" class="NewsFeedItem">
Example Url
<div class="attachedImage"></div>
</li>
<li id="#item-2" class="NewsFeedItem">
Example Url 2
<div class="attachedImage"></div>
</li>
<li id="#item-3" class="NewsFeedItem">
Example Url 3
<div class="attachedImage"></div>
</li>
...
</ol>
I want to use just one script to load content for each li. I wrote some code here but it isn't working
$('.NewsFeedItem').each(function() {
var id = $(this).get(0).id;
$('#' + id + '.attachedImage').load( $('#' + id + '.threadLink').attr('href') + ' .firstPost .messageText img' );
});
Where was I wrong?
Your code is fine, except at two points. To select the descendants, you need to separate the selectors by a space, which you are lacking in this line:
$('#' + id + ' .attachedImage').load( $('#' + id + ' .threadLink').attr('href') ...
A selector like #id.attachedImage will look for an element with ID as id, having a class attachedImage assigned to it.
If you want to select an element, having a class attachedImage assigned to it, and which is a descendant of an element of ID id, you need to write the selector as #id .attachedImage.
Edit 1:
Since the value in id already has a #, you need to remove the # from your selectors as well:
$( id + ' .attachedImage').load( $( id + ' .threadLink').attr('href') ...
Just Remove '#'
$( id + '.attachedImage').load( $( id + '.threadLink').attr('href') + '.firstPost .messageText img' );
Can you group those into one line, I know how to do this without concatenation but with, not working.
$('#vda'+event.target.id).remove();
$('#a'+event.target.id).remove();
$('#'+event.target.id).remove();
$('#da'+event.target.id).remove();
here is your one liner.
$(
'#vda' + event.target.id +
', #a' + event.target.id +
', #' + event.target.id +
', #da' + event.target.id
).remove();
it seems more, but I divided to better readability.
https://api.jquery.com/multiple-selector/ here is the documentation for multiple selector of jQuery
Try this
var str = ['#vda', '#a', '#', '#da'].join(event.target.id + ',') + event.target.id;
$(str).remove();
The join() method joins all elements of an array into a string.
str = arr.join([separator = ','])
or you can use reduce function
var str = ['#vda', '#a', '#', '#da'].reduce(function(p,c, i,arr){
if(i !== arr.length - 1)
return p + event.target.id + ',' + c
else
return p + event.target.id+ ',' + c + event.target.id
});
$(str).remove();
jQuery allows you to select as you do in CSS
So for the sake of an example, if you want to make a selector that matches all divs with test class, and all the p elements as well, in CSS you would select them using:
div.test, p { property:value }
In jQuery, do the same thing:
$("div.test, p").remove()
So you can just replace the div.test, p with whatever you selector you like
Here's a nice reference for CSS selectors
['vda','a','',da].forEach(function(val,key){
$('#'+event.target.id).remove();
})
If you do not have any extra elements with similar IDs, you can try ends with pattern selector:
$("[id$='pattern']")
$("#btn").on("click", function() {
var target = "test"; // e.target.id
$('[id$="test"]').remove();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div>
<div id="test">test</div>
<div id="atest">atest</div>
<div id="datest">datest</div>
<div id="vdatest">vdatest</div>
</div>
<button id="btn">Test</button>
You can try to make an array of all possible combinations and use map + join to get string
$("#btn").on("click", function() {
var target = "test"; // e.target.id
var selector_list = ["#", "#a", "#da", "#vda"];
var el_str = selector_list.map(function(item) {
return item + target;
}).join();
console.log(el_str);
$(el_str).remove();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div>
<div id="test">test</div>
<div id="atest">atest</div>
<div id="datest">datest</div>
<div id="vdatest">vdatest</div>
</div>
<button id="btn">Test</button>
Just for a record, you can do with pure JS selector API in ES6 style as follows;
[...document.querySelectorAll(['#vda','#a','#','#da'].join(",")].forEach(e => e.parentElement.removeChild(e));
I am a newbie to Jquery and trying to do the following.
I have an ID of an element which is generated by concatenation of a variable string. I need to select that element with this generated ID using JQuery. Please see below for more info..
Lets say I have elements with IDs as follows in a html Page
ID1=Test_A_element
ID2=Test_B_element
ID3=Test_C_element
ID4=Test_D_element
I have a string variable (x) that contains A or B or C or D. I will generate the ID of this element by simple concatenation as follows
ID="Test_"+x+"_element";
I need to select the correct Element using Jquery.
Using jQuery:
var jQuerySet = $("#" + ID);
Using the DOM:
var elem = document.getElementById(ID);
Live Example:
var ID =
"Test_" +
String.fromCharCode(65 + Math.floor((Math.random() * 4))) +
"_Element";
$("<p>").html("The ID is " + ID).appendTo(document.body);
$("#" + ID).css("color", "blue");
<div id="Test_A_Element">Test A</div>
<div id="Test_B_Element">Test B</div>
<div id="Test_C_Element">Test C</div>
<div id="Test_D_Element">Test D</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Check this page for more details about jQuery selectors: http://www.w3schools.com/jquery/jquery_ref_selectors.asp.
Or the more detailed official page: https://api.jquery.com/category/selectors/.
In your particular case, you can select an element by id with the following construction: jQuery("#"+ID), or $("#"+ID).
I need on selection to append div element to the another div, I have done it, and also every time when I select new selection, it should append new div.
the problem is, those appended div's have same id, so I can not delete particular element. I have made them unique with declaring var and combining id with a string, like : id="add_marke'+selectedKey+'" BUT I cant do something like this jQuery( "#add_marke'+selectedKey+'" ).click(function() {
How can I select ID when I make unique ID?
var selectedKey = jQuery("#model").val();
jQuery('#example').append('' + '<div class="add_marke" id="add_marke' +
selectedKey + '" >' +
' <div class="car_tag"><span class="lbl"><span id="car_name" class="icon-remove"></span></div> ' +
' ' +
' <select name="model_cars" id="model_cars" ><option id="selectModel" name="selectModel" value="all" >Please select </option><option>test</option></select>' +
' ' + '</div>');
jQuery("#car_name").click(function() {
jQuery("#add_marke\\.selectedKey").remove();
});
You can add the IDs as you do with a predefined prefix:
... id="add_marke_' + selectedKey + '" ...
And then bind the click with a jQuery selector for all elements that have the ID starting with add_marke_:
$('div[id^="add_marke_"]').click()
What you need to do is add the click handler to the class name shared by all of these divs. Once the click handler has been triggered, you can then extract the relevant id of the element and compose a selector from that id.
jQuery( ".class_name" ).click(function() {
var id = jQuery( this ).attr( "id" );
jQuery( "#" + id ).remove();
});
You can use
jQuery( ".icon-remove" ).click(function() {
jQuery(this).parent().parent().parent().remove();
});
Since an ID must be unique you have one of two options, as I see it:
Appending some sort of counter or numeric identifier to the ID, so you always have a unique ID (e.g., count the number of elements and then attribute your ID as my-id-1, my-id-2, etc.) Here you would have to write the DOM query in such a way that searches only for those IDs which begin with a given pattern, div[id^="my-id-"]
Use a class to identify the object in terms of any interactions you would like to provide for all of these <div> elements which have the same structure. Here, you can query based on a common class, in your case .add_marke.
<div class="parentElement">
<span>jagadeesh</span>
<span class="icon-remove car-remove"></span>
<button >Remove</button>
</div>
$('.car-remove').on('click',function(){
var mainElement = $(this).closest('.parentElement')
/// do what ever you want with main element. it selects only current parent
//element
mainElement.remove();
})
Did you want to do something like this?
http://jsfiddle.net/Wg9FE/1/
var selectedKey = "someId";
jQuery('#example').append('' +
'<div class="add_marke" id="add_marke'+selectedKey+'" >' +
' <div class="car_tag"><span class="lbl"><div id="car_name" class="icon-remove"></div></div> ' + ' ' +
' <select name="model_cars" id="model_cars" ><option id="selectModel" name="selectModel" value="all" >Please select </option><option>test</option></select>'+ ' ' +
'</div>');
jQuery( "#car_name" ).click(function() {
jQuery( "#add_marke" + selectedKey ).remove();
});
I have two divs
<div id = "first">some details111</div>
and
<div id = "second">some details222</div>
I want to create:
<div id ="New">some details111 some details222</div>
What is the best and the fast way to do it?
Using jQuery you could do that:
$(document).ready(function(){
$("body").append("<div id='New'></div>");
$("#New").text($("#first").text() + " " +$("#second").text());
});
Some vanilla JS for kicks and giggles:
// grab the content from our two divs
var content1 = document.getElementById('one').innerHTML;
var content2 = document.getElementById('two').innerHTML;
// create our new div, pop the content in it, and give it an id
var combined = document.createElement('div');
combined.innerHTML = content1 + " " + content2; // a little spacing
combined.id = 'new';
// 'container' can be whatever your containing element is
document.getElementById('container').appendChild(combined);
Try the below :
Fiddle Example : http://jsfiddle.net/RYh7U/99/
If you already have a DIV with ID "NEW" then try like below:
$('#New').html($('#first').html() + " " + $('#second').html())
If you want to Create a div and then add the Content then try like below.
$("body").append("<div id ='New'></div>")
$('#New').html($('#first').html() + " " + $('#second').html())
Well, using jQuery you can do by this way:
$("body").append(
$('<div/>')
.attr("id","New")
.html(
$("#first).html() + $("#second").html()
)
);
$("<div></div>").attr("id", "New").html($("#first").html() + $("#second").html()).appendTo($("body"));