Javascript get HTML of selected text nodes - javascript

I got the following HTML:
<div id="editable_phrase">
<span data-id="42">My</span>
<span data-id="43">very</span>
<span data-id="1">first</span>
<span data-id="21">phrase</span>
</div>
and I need to get the data-id attributes when I select (highlight) with a mouse these words. I use the following code:
var data = window.getSelection().getRangeAt(0).cloneContents();//this gets the data for all selected words
console.log(data);
It works fine except that when I select last word phrase, it selects only text without html contents. Any ideas how to fix that? I can use jQuery.
If I select 2 or 3 words, I need to get their data-ids respectively to each word, as it is with getRangeAt(0).cloneContents(). The problem is only with the last word, which does not return HTML code.
Thank you.

EDIT:
There has been a similar thread before, here is a working solution:
https://jsfiddle.net/hallleron/wg1pbwbf/2/
Basically you loop through the siblings in the selection to get each value and then parse the array as string to display it in my result paragraph for better visuals.
ORIGINAL:
If you want a jQuery-free version, here is a fiddle: https://jsfiddle.net/hallleron/wg1pbwbf/
The whole Javascript Part is the following:
document.getElementById('editable_phrase').addEventListener("click", getDataId);
function getDataId(){
console.log(window.getSelection().anchorNode.parentElement.attributes[0].nodeValue);
}
So every time the event listener detects a click, it gets the selected text/span and extracts its data-id attribute from the object.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="editable_phrase">
<span data-id="42">My</span>
<span data-id="43">very</span>
<span data-id="1">first</span>
<span data-id="21">phrase</span>
</div>
<script>
$('#editable_phrase').on('click','span',function(){
var res = $(this).attr('data-id');
alert(res);
})
</script>

Related

Javascript: How to print input to <div> selected by class?

Edit: Thanks for the helpful answers so far! I'm still struggling to print the input to the "right" div, though. What am I missing?
Next to the input field, there is an option to select either "left" or "right". Depending on the selection, the input is to be printed eiether left or right on the click of a button. This is what I have - but it only prints to the left, no matter the selection.
jQuery(document).ready(function(){
$('.button').click(function(){
$('.input').val();
if ($('select').val() == "left"){
$('div.left').html($('.input').val());
}
else {
$('div.right').html($('.input').val());
}
});
});
</script>
Sorry if this is very basic - I am completely new to JS and jQuery.
I'm trying to print input from a form into a div. This is part of the source HTML modify (it's for a university class):
<input type="text" class="input">
<div class="left">
</div>
<div class="right">
</div>
Basically, text is entered into the field, and I need to print this text either to the "left" or the "right" div when a button is clicked.
So far, I have only ever dealt with divs that had IDs, so I used
document.getElementById("divId").innerHTML = ($('.input').val());
But what do I do now when I don't have an ID? Unfortunately, changes to the HTML source are not an option.
Thanks in advance!
Just use normal selectors, like css and jQuery does.
https://api.jquery.com/category/selectors/
in your case:
$('div.left').html($('.input').val());
As you see there are many ways to do this. You can get elements by tag name, class, id...
But the most powerful way is to get it with querySelector
function save() {
var input = document.querySelector('input').value;
document.querySelector('div.left').innerHTML = input;
}
<input type="text" class="input">
<button onclick="save()">Save</button>
<div class="left"></div>
<div class="right"></div>
There are plenty of other ways to target HTML elements, but the one you're looking for in this case is getElementsByTagName(). Note that this returns a NodeList collection of elements, so you'll additionally need to specify the index that you wish to target (starting at 0). For example, if you want to target the second <div> element, you can use document.getElementsByTagName("div")[1].
This can be seen in the following example:
let input = document.getElementsByTagName("input")[0];
let button = document.getElementsByTagName("button")[0];
let div2 = document.getElementsByTagName("div")[1];
button.addEventListener("click", function(){
div2.innerHTML = input.value;
});
<input type="text">
<button>Output</button>
<br /><br />
<div>Output:</div>
<div></div>
Since you have unique class names for each element, document.getElementsByClassName can be used. This will return an array of elements containing the class. Since you only have one element with each class name, the first element of the returned array will be your target.
<input type="text" class="input">
<button onclick="save()">Save</button>
<div class="left"></div>
<div class="right"></div>
<script>
function save() {
var input = document.getElementsByClassName('input')[0].value;
document.getElementsByClassName('left')[0].innerHTML = input;
}
</script>
This is one of the many ways to do what you want:-
Write the following in console:
document.getElementsByTagName("div");
now you can see the total number of div elements used in your current document/page.
You can select one of your choice to work on by using "index number"(as in array index) for that particular div.
Lets say your div having class name = "right" is the 3rd one among the other div elements in your document.
This will be used to access that div element.
document.getElementsByTagName("right")[2].innerHTML = "whatever you want to write";

HTML Parsing using javaScript

I am trying to get parse HTML document.
this is the HTML:
<h1>
<span class="memName fn" itemprop="name">Ankur Arora</span>
<span class="display-none" itemprop="image">http://photos1.meetupstatic.com/photos/member/3/8/f/8/member_249974584.jpeg</span>
<span class="display-none" itemprop="url">http://www.meetup.com/Meetup-API-Testing/members/191523682/</span>
</h1>
I need to get the picture and the name.
I try this code:
var name = document.querySelector("memName fn").name;
Anyone can help me? I'm new in javaScript...
Thanks
To get the inner text, you can use the text() function, like this:
HTML:
<span class="memName fn">Ankur Arora</span>
Jquery:
var memName = $(".memName").text();
console.log(memName); // Via console log
alert(memName); // Alert it
It's easy with jQuery. Just include it in your page:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
Then use .text() or .html() to extract the content of the span-elements
var pictureLink = $("span[itemprop='image']").text();
//.html() also gets the html-elements inside
var name = $("span[itemprop='name']").html();
https://jsfiddle.net/bh9mebru/
You can also use innerHTML to get the text.
<span id="memId" class="memName fn">Ankur Arora</span>
document.getElementsByClassName('memName') - This will give the list of elements having the class 'memName'
To get the first element's inner text use document.getElementsByClassName('memName')[0].innerHTML
or access by id .
document.getElementById('memId').innerHTML

Get the Text inside the element

<p class="MsoNormal" style="margin-bottom:0cm;margin-bottom:.0001pt;text-align:
justify;line-height:normal">
First Text
<span lang="EN-US" style="font-size:12.0pt;
font-family:"Times New Roman","serif"">
Second Text</span>
</p>
This is my code, how to get the content inside the paragraph tag. [The tag may change to div or ul]. I need all the content inside the paragraph tag by javascript.
The output should be :
First Text Second Text
Sorry I am new to javascript, searched but cant find answer for this relevant problem. Thanks
To get the value of a tag, you can get the element with a selector and use innerHTML to get the value. like this:
<p>hi there</p>
console.log(document.getElementsByTagName('p')[0].innerHTML);
n.b. in the code above it's selecting by tag name, so it returns an array of matching elements
So in your example, using .innerHTML with give you the P tags content, including any html tags etc.
if you want just the content, you can use .textContent
console.log(document.getElementsByTagName('p')[0].textContent);
This wont give you the inner html tags
n.b. there is also the innerText method, However this isnt supported accross browsers.
You can change according to the tag you need, but basically this will do the trick:
document.getElementsByTagName('p')[0].innerText
Fiddle
InnerText should be a good solution.
console.log(document.getElementsByTagName('p')[0].innerText);
<p class="MsoNormal" style="margin-bottom:0cm;margin-bottom:.0001pt;text-align:
justify;line-height:normal">
First Text
<span lang="EN-US" style="font-size:12.0pt;
font-family:"Times New Roman","serif"">
Second Text</span>
</p>

how to display text in div dynamically

I have searched on the forum and saw posts about changing text dynamically upon click. But in my case I want to change the display dynamically when loading the page from beginning. I already have a function that figure out what I should display:
function phone()
{
//code here
return phone;
}
And my question is how to display the returned phone number in the div below to replace the 1.888.888.8888 part. Can anyone offer some insights? Thank you!
<div class="add-info">
<span class="rightfloat">Order online <span class="red">or call 1.888.888.8888</span></span>
</div>
I would change the HTML to add another <span> tag around the phone number and give that span tag an id attribute in order to access it easily (broke it up on separate lines to reduce scrolling):
<div class="add-info">
<span class="rightfloat">
Order online <span class="red">
or call <span id="contact-number"></span>
</span>
</span>
</div>
Then after the page loads update the span with whatever value you want:
window.onload = function() {
document.getElementById('contact-number').innerHTML = PHONE_NUMBER_VALUE;
}
In JQuery, it would be:
$(document).ready(function () {
$('#contact-number').html(PHONE_NUMBER_VALUE);
});
You can,
<body onload="phone();">
<div class="add-info">
<span class="rightfloat">Order online <span class="red">or call
<span id="phone"></span>
</span>
</div>
</body>
And set the value when the function runs;
function phone() {
document.getElementById("phone").innerHTML = "1.888.888.8888";
}
Instead of returning 'phone', why don't you put an id on your span and just use
document.getElementById('spanId').innerHTML = phone
in your javascript?
Call you code from the window.onload event.
I would separate the number into additional <span> tag with its own id and change content of it with js...
document.getElementById('id_of_span').innerText = 'new number';
Try this
<script>
function phone(number) {
var redText = document.getElementByClassname("red")[0];
redText.innerHTML = "or call " + number;
}
</script>
To call it you can use clicks, loads or anything else. For example
<script>
window.onload = phone('NEW NUMBER HERE');
</script>
Bear in mind that adding another window onload function later will displace this one, so you would either need to add to it, or use a double delegate function, but that's another story...

Data only to click the div

Good morning, everyone.
I have a doubt. I have a list of div. textarea with text inside it and inside. text for a button event. Want to get only the data from the textarea div that the person clicking the button.
I would be very grateful for the help. thanks
Example code.
<div class="text">
<textarea id="texts" class="texts" rows="5" cols="45" name="textarea"> </ textarea>
<div class="bt" id="1234556">
<div class="button"> Send </div>
</div>
</div>
$('.button').click(function() {
var text = $('#texts').val();
// do something with text
alert(text);
});
Working demo at http://jsfiddle.net/PPcxm/
As long as you have the same structure (and presuming you have more than one example on the page as the button is a class and textarea is an id, the following would work:
$(".button").click(function()
{
var text = $(this).parent().prev().val();
});
Since you have a list of div.text your best bet is to query based upon the structure of your DOM.
$(".button").click(function() {
var $textArea = $(this).parents(".text").find(".texts");
//Do something with $textArea.Val();
});
What we simply do is call .parents() on the current div.button which will allow us to get the div.text element. From there you can simply find your textarea.texts element and get the corresponding value.
Code example on jsfiddle.

Categories