For each element with a certain attribute - Javascript - javascript

I try to find all elements whith a particular attribute. For each elements, I want to do something dependant of the value of the attribute.
I did a test to take back the value of the attribute but it doesn't work and I don't see the problem.
HTML:
<div id="t">Test</div>
<div data-test="One">Value One</div>
<div data-test="Two">Value Two</div>
JS:
$("[data-test]").each(function(){
$("#t").append(this.attr("data-test"));
});
JsFiddle link: http://jsfiddle.net/fbue5dpc/
Thank you!

this in your each block refers to the DOM element which does not have the attr method. You should use $(this) to convert it to a jQuery object. You can also improve this further by using the data method to retrieve the values and caching the #t element to reduce the number of DOM retrievals being made:
var $t = $('#t')
$("[data-test]").each(function(){
$t.append($(this).data('test'));
});
Updated fiddle

var elemnt = $("[data-test]"),frag = "";
elemnt.each(function () {
frag += $(this).attr("data-test");
});
$("#t").append(frag);
Working DEMO

Try,
$(this).attr("data-test")
Explanation: inside the foreach loop you will get dom element since you are iterating list of dom element. So you cant invoke jquery method directly from dom elemet to do this you have to convert it into a jquery object to do this just use $(this)

$("div[id!='t']").each(function(){
$("#t").append($(this).data('data-test'));
}

Related

jQuery find not working in top-level elements if not added to DOM

I'm loading some HTML with jQuery asynchronously:
$.get(path, {}, function (data) {
var result = $(data);
var resultSelector = result.find(selector);
});
result is a valid HTML that contains my selector (in my specific case, "#UsersAndRolesResults").
I can see that it contains when I simply type result into the console, it's there exactly with the same ID, no typos or anything.
However, result.find(selector) returns 0 elements.
In my specific example, this is result:
And:
Why?
UPDATE: I can query for other elements that are inside #UsersAndRolesResults with their ID tag and they are returned correctly. I also cannot query any other top-level elements in the result. I think there is an issue with querying top-level elements inside the result.
UPDATE 2: Just try $('<div id="target"></div>').find("#target") and you will get 0 results, where you should obviously get the div.
No. This is not bug, this is behavior defined in jQuery.
find() is used to select the elements which are inside the element on which find is called. In your case, the element is not children of the selector, so find will not work.
Example:
<div id="container">
<div class="message">Hello World!</div>
<div>Bye World</div>
</div>
JavaScript:
$('#container').find('.message');
This will select the element having class message and which is inside the element having ID container.
But, if you use find, it'll return nothing i.e. empty array since there is no element #container inside #container.
$('#container').find('#container');
Your code is equivalent to this ^^^.
If you want, you can use filter. filter will go through each element and check if this matches the selector, if it then the element is added to the result set.
$('#container').filter('#container');
This'll give you complete element.
It seems to be a design decision with jQuery. Top-level elements in an AJAX result are not queried correctly with find. Interesting.
I've solved my problem with a workaround by creating a dummy div element, encapsulating my result inside that element, and then querying that dummy element. It worked:
var t = $("<div>")
t.append(result);
t.find("#UsersAndRolesResults"); //this one returned my object correctly
For a simple example, try:
$('<div id="target"></div>').find("#target");
You will get 0 results.
Try:
$('<div><div id="target"></div></div>').find("#target")
And you'll get the correct result.
Try this:
$.get(path, {}, function (data) {
var result = $($.parseHTML(data));
var resultSelector = result.find(selector);
});
Given
console.log($("<div id=target></div>").find("#target"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
.length would be 0 as expected.
You can use .closest() to search for both child elements and original jQuery object selector
console.log($("<div id=target></div>").closest("#target"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

prev() not returning div element

I'm probably being especially dense about this, but I can't get an element to return using prev(). My basic HTML structure is:
<div>
<table></table>
</div>
<input type="button">
Where when I press the button, I want to get the previous element (the div element). To achieve this my button has a function attached to it with
var nearestDiv = $(this).prev();
When I've checked the contents of nearestDiv in the console it appears to be some kind of JQuery object rather than a HTML div. I've tried popping .val() at the end of .prev() but this comes back empty. How can I get the div element?
Note that my button is generated on the fly and doesn't have anything which identifies it.
you need to use jquery get function, to get a native html object and not the jquery wrapper:
$("input").on("click",function(){
console.log("jquery wrapper:",$(this).prev());
console.log("native html div object:",$(this).prev().get(0));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<table></table>
</div>
<input type="button">
If your html structure is same as you provided in the question, it will definitely return the div element. Note that there is no val() method for div element, you need to either use .html() or .text() inorder to get the contents.
$("input[type='button']").click(function () {
var div = $(this).prev();
alert(div.html());
alert(div.text());
});
Fiddle
You need to give .text() or .html() for standard HTML Elements. So your code should be:
var nearestDiv = $(this).prev().html();
var nearestDiv = $(this).prev().text();

Put an id to a parent element

I wanted to put an id in my element's parent element. Below is my code:
<div>
<div id="child"></div>
<div>
Im aware that jquery has a way to select a parent element , but I dont know how what method shall I use to put an id to it. Below is my jquery code:
div_resizable = $( "#child" ).parent();
div_resizable.id = "div_resizable";
Above code doesnt work with me. It doesnt throw an error, but no changes had taken effect. Any solution to my problem?
For achieve what you want, you can use the jquery attr:
$("#child" ).parent().attr('id', 'newID');
Or you can use the prop:
$("#child" ).parent().prop('id', 'newID');
And you can check the difference between the two here: difference between prop() and attr()
Of course div_resizable.id = "div_resizable" doesn't work. div_resizeable is an jQuery array and you are trying to assign id to it.
Try .attr instead:
$("#child").parent().attr({id: "div_resizable"});
To set a property on the first element inside a jQuery result object:
div_resizable = $( "#child" ).parent()[0];
// ^^^
div_resizable.id = "div_resizable";
This picks the first Element from the result so that you can directly access the property.
Or:
$('#child').parent().prop('id', 'div_resizable');
Use the .prop() helper method to accomplish the same thing.

Is there a way to modify a specific attribute of every jquery object in one call?

Basically.... I am using this code
var editorLinks;
editorLinks = $(".admin_editor_link.html");
$.each(editorLinks, function(i, link){
$(link).html($(link).attr("data-loadedtext"));
});
And I am wondering if there is some way to do it without the $.each call... like...
editorLinks.html($(this).attr("data-loadedtext"));
I assumed this would work (or some variation of it that I cant remember) but when I tried it all elements html was set to the data-loadedtext of the first element in the array.
Use a function supplied to html():
editorLinks.html(function(){
return $(this).attr("data-loadedtext");
});
The return value of the function is used as the value for html() for each element.
Using your example HTML in comment:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/taesc0tt/2/
Yes, you can, but you'll need to change the name of your class to admin_editor_link because jQuery selector is trying to find elements with both admin_editor_link and html classes. (Unless, of course, you actually looking for elements with both those classes - your question has no HTML code to verify that - in which case you're fine).
<div data-loadedtext="1" class="admin_editor_link"></div>
<div data-loadedtext="2" class="admin_editor_link"></div>
Just use a function to return the result
var editorLinks = $(".admin_editor_link");
editorLinks.html(function () {
return $(this).attr("data-loadedtext");
});
DEMO
DEMO with both classes

Creating a div element in jQuery [duplicate]

This question already has answers here:
jQuery document.createElement equivalent?
(14 answers)
Closed 5 years ago.
How do I create a div element in jQuery?
As of jQuery 1.4 you can pass attributes to a self-closed element like so:
jQuery('<div>', {
id: 'some-id',
class: 'some-class some-other-class',
title: 'now this div has a title!'
}).appendTo('#mySelector');
Here it is in the Docs
Examples can be found at jQuery 1.4 Released: The 15 New Features you Must Know .
You can use append (to add at last position of parent) or prepend (to add at fist position of parent):
$('#parent').append('<div>hello</div>');
// or
$('<div>hello</div>').appendTo('#parent');
Alternatively, you can use the .html() or .add() as mentioned in a different answer.
Technically $('<div></div>') will 'create' a div element (or more specifically a DIV DOM element) but won't add it to your HTML document. You will then need to use that in combination with the other answers to actually do anything useful with it (such as using the append() method or such like).
The manipulation documentation gives you all the various options on how to add new elements.
d = document.createElement('div');
$(d).addClass(classname)
.html(text)
.appendTo($("#myDiv")) //main div
.click(function () {
$(this).remove();
})
.hide()
.slideToggle(300)
.delay(2500)
.slideToggle(300)
.queue(function () {
$(this).remove();
});
div = $("<div>").html("Loading......");
$("body").prepend(div);
$("<div/>").appendTo("div#main");
will append a blank div to <div id="main"></div>
A short way of creating div is
var customDiv = $("<div/>");
Now the custom div can be appended to any other div.
All these worked for me,
HTML part:
<div id="targetDIV" style="border: 1px solid Red">
This text is surrounded by a DIV tag whose id is "targetDIV".
</div>
JavaScript code:
//Way 1: appendTo()
<script type="text/javascript">
$("<div>hello stackoverflow users</div>").appendTo("#targetDIV"); //appendTo: Append at inside bottom
</script>
//Way 2: prependTo()
<script type="text/javascript">
$("<div>Hello, Stack Overflow users</div>").prependTo("#targetDIV"); //prependTo: Append at inside top
</script>
//Way 3: html()
<script type="text/javascript">
$("#targetDIV").html("<div>Hello, Stack Overflow users</div>"); //.html(): Clean HTML inside and append
</script>
//Way 4: append()
<script type="text/javascript">
$("#targetDIV").append("<div>Hello, Stack Overflow users</div>"); //Same as appendTo
</script>
$("<div/>").attr('id','new').appendTo('body');
This will create new div with id "new" into body.
document.createElement('div');
Here's another technique for creating divs with jQuery.
ELEMENT CLONING
Say you have an existing div in your page that you want to clone using jQuery (e.g. to duplicate an input a number of times in a form). You would do so as follows.
$('#clone_button').click(function() {
$('#clone_wrapper div:first')
.clone()
.append('clone')
.appendTo($('#clone_wrapper'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clone_wrapper">
<div>
Div
</div>
</div>
<button id="clone_button">Clone me!</button>
Create an in-memory DIV
$("<div/>");
Add click handlers, styles etc - and finally insert into DOM into a target element selector:
$("<div/>", {
// PROPERTIES HERE
text: "Click me",
id: "example",
"class": "myDiv", // ('class' is still better in quotes)
css: {
color: "red",
fontSize: "3em",
cursor: "pointer"
},
on: {
mouseenter: function() {
console.log("PLEASE... "+ $(this).text());
},
click: function() {
console.log("Hy! My ID is: "+ this.id);
}
},
append: "<i>!!</i>",
appendTo: "body" // Finally, append to any selector
}); // << no need to do anything here as we defined the properties internally.
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Similar to ian's answer, but I found no example that properly addresses the use of methods within the properties object declaration so there you go.
simply if you want to create any HTML tag you can try this
for example
var selectBody = $('body');
var div = $('<div>');
var h1 = $('<h1>');
var p = $('<p>');
if you want to add any element on the flay you can try this
selectBody.append(div);
<div id="foo"></div>
$('#foo').html('<div></div>');
If you are using Jquery > 1.4, you are best of with Ian's answer. Otherwise, I would use this method:
This is very similar to celoron's answer, but I don't know why they used document.createElement instead of Jquery notation.
$("body").append(function(){
return $("<div/>").html("I'm a freshly created div. I also contain some Ps!")
.attr("id","myDivId")
.addClass("myDivClass")
.css("border", "solid")
.append($("<p/>").html("I think, therefore I am."))
.append($("<p/>").html("The die is cast."))
});
//Some style, for better demonstration if you want to try it out. Don't use this approach for actual design and layout!
$("body").append($("<style/>").html("p{background-color:blue;}div{background-color:yellow;}div>p{color:white;}"));
I also think using append() with a callback function is in this case more readable, because you now immediately that something is going to be appended to the body. But that is a matter of taste, as always when writing any code or text.
In general, use as less HTML as possible in JQuery code, since this is mostly spaghetti code. It is error prone and hard to maintain, because the HTML-String can easily contain typos. Also, it mixes a markup language (HTML) with a programming language (Javascript/Jquery), which is usually a bad Idea.
alternatively to append()
you can also use appendTo() which has a different syntax:
$("#foo").append("<div>hello world</div>");
$("<div>hello world</div>").appendTo("#foo");
You can create separate tags using the .jquery() method. And create child tags by using the .append() method. As jQuery supports chaining, you can also apply CSS in two ways.
Either specify it in the class or just call .attr():
var lTag = jQuery("<li/>")
.appendTo(".div_class").html(data.productDisplayName);
var aHref = jQuery('<a/>',{
}).appendTo(lTag).attr("href", data.mediumImageURL);
jQuery('<img/>',{
}).appendTo(aHref).attr("src", data.mediumImageURL).attr("alt", data.altText);
Firstly I am appending a list tag to my div tag and inserting JSON data into it. Next, I am creating a child tag of list, provided some attribute. I have assigned the value to a variable, so that it would be easy for me to append it.
I think this is the best way to add a div:
To append a test div to the div element with ID div_id:
$("#div_id").append("div name along with id will come here, for example, test");
Now append HTML to this added test div:
$("#test").append("Your HTML");
I hope that helps code. :) (I use)
function generateParameterForm(fieldName, promptText, valueType) {
//<div class="form-group">
//<label for="yyy" class="control-label">XXX</label>
//<input type="text" class="form-control" id="yyy" name="yyy"/>
//</div>
// Add new div tag
var form = $("<div/>").addClass("form-group");
// Add label for prompt text
var label = $("<label/>").attr("for", fieldName).addClass("control-label").text(promptText);
// Add text field
var input = $("<input/>").attr("type", "text").addClass("form-control").addClass(valueType).attr("id", fieldName).attr("name", fieldName);
// lbl and inp => form
$(form).append(label).append(input);
return $(form);
}
If it is just an empty div, this is sufficient:
$("#foo").append("<div>")
or
$("#foo").append("<div/>")
It gives the same result.
$(HTMLelement) can success it. If you want an epmty div use it as $('<div></div>');. Also you can set the other elements by the same method. If you want to change inner HTML after created you can use html() method. For get outerHTML as string you can use is like this :
var element = $('<div/>');
var innerHTML = element.html(); // if you want set new HTML use it like this element.html('<b>new HTML</b>');
var outerHTML = element[0].outerHTML;
You can use .add() to create a new jQuery object and add to the targeted element. Use chaining then to proceed further.
For eg jQueryApi:
$( "div" ).css( "border", "2px solid red" )
.add( "p" )
.css( "background", "yellow" );
div {
width: 60px;
height: 60px;
margin: 10px;
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
How about this? Here, pElement refers to the element you want this div inside (to be a child of! :).
$("pElement").append("<div></div");
You can easily add anything more to that div in the string - Attributes, Content, you name it. Do note, for attribute values, you need to use the right quotation marks.
I've just made a small jQuery plugin for that.
It follows your syntax:
var myDiv = $.create("div");
DOM node ID can be specified as second parameter:
var secondItem = $.create("div","item2");
Is it serious? No. But this syntax is better than $("<div></div>"), and it's a very good value for that money.
(Answer partially copied from: jQuery document.createElement equivalent?)

Categories

Resources