Jquery find operations on dynamic html - javascript

I create dynamic html content (table rows). td elements have class assigned to it depending on the row.
I want to perform multiple find element by class and perform .text() and style operations and then append final html to the table body.
I tried this and does not work. Please help.
function processrow(html){
$(html).find(".item1").text('Closed');
$(html).find(".item5").css('background-color', '#66a666');
return html;
}
example value passed to function
<tr><td>row1</td><td class="item1"></td></tr>
Need it return
<tr><td>row1</td><td class="item1">Closed</td></tr>
Added fiddle - http://jsfiddle.net/6mnLwg0o/2/

First create the jQuery object with the source by doing $(html), then make the changes to the inner elements with find(). In the example below I am appending the updated html to a test div so that you can see the result.
HTML:
<div id="test"></div>
JavaScript:
var src = processrow('<table><tr><td class="item5">row1</td><td class="item1"></td></tr></table>');
src.appendTo($('#test'));
function processrow(html) {
var obj = $(html);
obj.find(".item1").text('Closed');
obj.find(".item5").css('background-color', '#66a666');
return obj;
}
Demo: http://jsfiddle.net/BenjaminRay/td00gssw/

When you say $(html) it creates a dom structure based on the html which is then modified. Change done in the dom after that will not get reflected in the source html, so to get the modified html you need to get the html from the dom objects.
function processrow(html) {
var $div = $('<div />', {
html: html
});
$div.find(".item1").text('Closed');
$div.find(".item5").css('background-color', '#66a666');
return $div.html();
}

Related

How to receive data attribute with jsoup?

i need to get data attribute from html
I am trying to get like this
Elements element = document.select("div.highlight padding standard-box");
result+= element.attr("data-highlight-embed");
But result is empty, should be data-highlight-embed = content
html-code
<div class="highlight padding standard-box" data-link-tracking-page="Matchpage"
data-link-tracking-column="[Main content]" data-link-tracking-destination="Click on highlight [button]"
data-highlight-embed="content">text</div>
You need to change your CSS query and notice that the select() method return multiple elements.
Update the CSS query to
Elements element = document.select("div.highlight.padding.standard-box");
Then you can loop the result
for(Element el : element) {
System.out.println(el.attr("data-highlight-embed"));
}
Or you can get the first element
System.out.println(element.first().attr("data-highlight-embed"));
To get the data attributes you also can reference how to use dataset() method at https://simplesolution.dev/java-jsoup-extract-custom-data-attributes-html5-element/

For each element with a certain attribute - 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'));
}

javascript elements/tags array DOM node access

what's the different between using:
// assuming using elements/tags 'span' creates an array and want to access its first node
1) var arrayAccess = document.getElementsByTagName('elementName')[0]; // also tried property items()
vs
// assuming I assign an id value to the first span element/tag
// specifically calling a node by using it's id value
2) var idAccess = document.getElementById('idValue');
then if I want to change the text node....when using example 1) it will not work, for example:
arrayAccess.firstChild.nodeValue = 'some text';
or
arrayAccess.innerText/innerHTML/textContent = 'some text';
If I "access" the node through its id value then it seems to work fine....
Why is it that when using array it does not work? I'm new to javascript and the book I'm reading does not provide an answer.
Both are working,
In your first case you need to pass the tag name instead of the element name. Then only it will work.
There might be a case that you trying to set input/form elements using innerHTML. At that moment you need to use .value instead of innerHTML.
InnerHTML should be used for div, span, td and similar elements.
So your html markup example:
<div class="test">test</div>
<div class="test">test1</div>
<span id="test">test2</span>
<button id="abc" onclick="renderEle();">Change Text</button>
Your JS code:
function renderEle() {
var arrayAccess = document.getElementsByTagName('div')[0];
arrayAccess.innerHTML = "changed Text";
var idEle = document.getElementById('test');
idEle.innerHTML = "changed this one as well";
}
Working Fiddle
When you use document.getElementsByTagName('p'), the browser traverses the rendered DOM tree and returns a node list (array) of all elements that have the matching tag.
When you use document.getElementById('something'), the browser traverses the rendered DOM tree and returns a single node matching the ID if it exists (since html ID's are unique).
There are many differences when to use which, but one main factor will be speed (getElementById is much faster since you're only searching for 1 item).
To address your other question, you already have specified that you want the first element in the returned nodeList (index [0]) in your function call:
var arrayAccess = document.getElementsByTagName('elementName')[0];
Therefore, arrayAccess is already set to the first element in the returned query. You should be able to access the text by the following. The same code should work if you used document.getElementById to get the DOM element:
console.log(arrayAccess.textContent);
Here's a fiddle with an example:
http://jsfiddle.net/qoe30w2w/
Hope this helps!

use of Jquery .after() for moving an element around

I'm reading the jquery manual regarding the .after() function:
$('.container').after($('h2'));
and it says
"If an element selected this way is inserted elsewhere, it will be
moved rather than cloned"
So if I have multiple
<div class='before' onclick='afterfunction();'><div>,
and I would want to place <div class='after'></div> after whichever div is clicked (have it move, not clone) would I do something like this?
var afterdiv = "<div class='after'></div>";
function afterfunction() {
$(this).after(afterdiv);
}
Thanks for all your help!
Like you said:
An element in the DOM can also be selected and inserted after another element:
$('.container').after($('h2'));
If an element selected this way is inserted elsewhere,
it will be moved rather than cloned:
But you missed the bold part.
$('.before').click(function() {
afterfunction(this);
});
// this will not work cause you'll append a string to your DOM
// var afterdiv = "<div class='after'>ola</div>";
// and will repeatedly be appended after each action.
// instead define your element by wrapping it into a $( )
var afterdiv = $("<div class='after'>ola</div>");
// now 'afterdiv' variable is binded to that element only once inside the DOM
function afterfunction(elem) {
$(elem).after(afterdiv);
}
And you don't need to .remove() it (like wrongly suggested in an answer here.)
demo jsFiddle
Make .before div like this:
<div class='before'><div/>
Then try,
$('.before').on('click', function() {
afterfunction(this);
});
function afterfunction(el) {
var afterdiv = "<div class='after'></div>";
$('.after').remove(); // remove previous `.after`
$(el).after(afterdiv); // add newly after the clicked div
}
DEMO

Javascript to get elements by their attributes

<body>
<span someAttribute="xyz">.....</span>
...
<div>
...
<span someAttribute="abc">.....</span>
...
<div someAttribute="pqr">.....</div>
...
</div>
</body>
Here is a sample html page.. I need to select the html elements by its attributes i can get the attribute values by getAttribute() but i need to select all the elements first.
How in javascript to get elements which has the attribute name as "someAttribute". Once i get the elements i can get the attribute values and use my function.
Note: i want to do this without using jquery.
In new browsers you can do:
var el = document.querySelector('[someAttribute="someValue"]');
store each element in a array the loop throught each element, and if the element contains the attribute someAttribute do somgthing.
var arr_elms = [];
arr_elms = document.body.getElementsByTagName("*");
var elms_len = arr_elms.length;
for (var i = 0; i < elms_len; i++) {
if(arr_elms[i].getAttribute("someAttribute") != null){
alert("FOUND : " + arr_elms[i].getAttribute("someAttribute"));
}
}
You can select elements by tag name using document.body.getElementsByTagName("div") to get all the div elements inside your document. This function returns an array of elements, which you can parse and filter out elements that don't match your criteria.
You can traver all elements of DOM tree.
you can use
var all = document.getElementsByTagName('*');
but this also returns the html, head and body ...
and then do a loop over all elements and look for the attributes.
I found a snippet called getElementsByAttribute(doc, tagArray, attribute, attributeValue)
You can give a try to a working fiddle: http://jsfiddle.net/Yx7EU/
Hope this can help.

Categories

Resources