How to receive data attribute with jsoup? - javascript

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/

Related

Select element by data defined with jquery

I'm trying to select element by data attribute defined with jquery (it's not visible in DOM), therefore I cannot use $('.foo:data(id)')
example: if user clicks element I add data property to it as following
$(this).data('id', '1');
now I would like to find element which has
data-id == 1
how can I select this element by data-id?
Use filter()
$('.foo').filter(function(){
return $(this).data('id') === `1`
}).doSomething()
You could use the attribute selector [attribute=...].
In your case, this would be
$('[data-id=1]')
But keep in mind, if you change the data of an element with .data(), the change isn't reflected in the dom attribute, so you can't use this (or additionally change the dom attribute).
The other way would be to select every candidate and then filter for each element, which has a matching data value.
$('.foo').filter(function(){
return $(this).data('id') == 1;
});

Jquery find operations on dynamic html

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();
}

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!

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.

Parse string for text between divs

I have a string of html text stored in a variable:
var msg = '<div class="title">Alert</div><div class="message">New user just joined</div>'
I would like to know how I can filter out "New user just joined" from the above variable in jQuery/Javascript so that I can set the document title to just the message.
Like this:
document.title = $(msg).filter("div.message").text();
Note that if the message changes to be wrapped in an element, you'll need to replace filter with children.
EDIT: It looks like the div that you want is nested in other element(s).
If so, you can do it like this:
document.title = $("div.message", msg).text();
Explanation: $('<div>a</div><div>b</div>') creates a jQuery object holding two different <div> elements. You can find the one you're looking for by calling the filter function, which finds mathcing elements that are in the jQuery object that you call it on. (Not their children)
$('<p><div>a</div><div>b</div><p>') creates a jQuery object holding a single <p> element, and that <p> element contains two <div> elements as children. Calling $('selector', 'html') will find all descendants of the elements in the HTML that match the selector. (But it won't return the root element(s))
This is a hack and not very clean, but it should work:
add a div node and set its html to your text message,
get the text of the added element and store it in a variable
destroy the node
set the title with the contents of the variable in step 2

Categories

Resources