I am trying to fetch text embedded with <Label> tag. I have zero to very basic knowledge of Javascript and JQuery so I need guidance on this. I am trying this code which have copied from another stackoverflow post get-values-from-label-using-jquery
<label year="2010" month="6" id="currentMonth"> June 2010</label>
var label = $('#currentMonth');
var month = label.attr('month');
var year = label.attr('year');
var text = label.text();
The problem with this code is, as soon as I remove ID element it stops working. Please advise me, How can i get this working without ID element?
Use class instead of Id to target the element
var label = $('.currentMonth');
var month = label.attr('month');
var year = label.attr('year');
var text = label.text();
console.log(month,year,text)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<label year="2010" month="6" class="currentMonth"> June 2010</label>
The way of using pure JavaScript:
HTML:
<label year="2010" month="6" class="currentMonth"> June 2010</label>
JavaScript:
let label = document.getElementsByClassName('currentMonth')[0];
let month = label.getAttribute('month');
let year = label.getAttribute('year');
let text = label.textContent;
console.log(month,year,text)
At your disposal, you've got a string of methods to work with DOM. An easy way to get your element is using:
document.getElementsByTagName("add-your-tag-label-in-this-case");
https://www.w3schools.com/jsref/met_document_getelementsbytagname.asp
Related
I am having trouble getting the input values from a div that I appended. It returns as undefined. So basically I am creating the input element and giving it an Id. I have a function that when I clicked a button it is suppose to show the input value..
I am relatively new to JavaScript and I can't seem to find any solution for this. Please help me.. thank you
I am currently doing this in the same JavaScript script so there is no HTML script.
var question1ProjectTitleDiv = document.createElement("div");
var question1ProjectTitle= document.createElement("span")
var question1ProjectTitleName= document.createTextNode("Project Title:")
var question1ProjectTitleInput = document.createElement("input");
question1ProjectTitleInput.type= "text"
question1ProjectTitleInput.maxLength = 256;
question1ProjectTitleInput.id="question1ProjectTitleInputID"
question1ProjectTitleDiv.append(question1ProjectTitle)
question1ProjectTitle.append(question1ProjectTitleName)
question1ProjectTitleDiv.append(question1ProjectTitleInput)
questions.append(question1ProjectTitleDiv) //Add project title
console.log(question1ProjectTitleInput) // Returns <input type="text" maxlength="256" id="question1ProjectTitleInputID">
JS CODE:
let question1ProjectTitleInputID = $("#question1ProjectTitleInputID").val(); //Jquery
let question1ProjectTitleInputID2 = document.getElementById('question1ProjectTitleInputID') //Vanilla JS
You have the following statement:
question1ProjectTitleInput.id="question1ProjectTitleInputID"
So, if you use jquery to read the input, you should
let question1ProjectTitleInputID = $("#question1ProjectTitleInputID").val(); //Jquery
I have an HTML article with some annotations that I retrieve with SPARQL queries. These annotations refer to some text in the document, and I have to highlight this text (wrapping it in a span).
I had already asked how to wrap text in a span, but now I have a more specific problem that I do not know how to solve.
The code I wrote was:
var currentText = $("#"+v[4]["element"]+"").text();
var newText = currentText.substring(0, v[5]["start"]) + "<span class=' annotation' >" + currentText.substring(v[5]["start"], v[6]["end"]) + "</span>" + currentText.substring(v[6]["end"], currentText.length);
$("#"+v[4]["element"]+"").html(newText);
Where:
v[4]["element"] is the id of the parent element of the annotation
v[5]["start"] is the position of the first character of the annotation
v[6]["end"] is the position of the last character of the annoation
Note that start and end don't consider html tags.
In fact my mistake consists in extracting data from the node with the text() method (to be able to go back to the correct position of the annotation) and put back with the html() method; but in this manner if parent node has children nodes, they will be lost and overwritten by simple text.
Example:
having an annotation on '2003'
<p class="metadata-entry" id="k673f4141ea127b">
<span class="generated" id="bcf5791f3bcca26">Publication date (<span class="data" id="caa7b9266191929">collection</span>): </span>
2003
</p>
It becomes:
<p class="metadata-entry" id="k673f4141ea127b">
Publication date (collection):
<span class="annotation">2003</span>
</p>
I think I should work with nodes instead of simply extract and rewrite the content, but I don't know how to identify the exact point where to insert the annotation without considering html tags and without eliminating child elements.
I read something about the jQuery .contents() method, but I didn't figure out how to use it in my code.
Can anyone help me with this issue? Thank you
EDIT: Added php code to extract body of the page.
function get_doc_body(){
if (isset ($_GET ["doc_url"])) {
$doc_url = $_GET ["doc_url"];
$doc_name = $_GET ["doc_name"];
$doc = new DOMDocument;
$mock_doc = new DOMDocument;
$doc->loadHTML(file_get_contents($doc_url.'/'.$doc_name));
$doc_body = $doc->getElementsByTagName('body')->item(0);
foreach ($doc_body->childNodes as $child){
$mock_doc->appendChild($mock_doc->importNode($child, true));
}
$doc_html = $mock_doc->saveHTML();
$doc_html = str_replace ('src="images','src="'.$doc_url.'/images',$doc_html);
echo($doc_html);
}
}
Instead of doing all these, you can either use $(el).append() or $(el).prepend() for inserting the <span> tag!
$("#k673f4141ea127b").append('<span class="annotation">2003</span>');
Or, If I understand correctly, you wanna wrap the final 2003 with a span.annotation right? If that's the case, you can do:
$("#k673f4141ea127b").contents().eq(1).wrap('<span class="annotation" />');
Fiddle:
$(document).ready(function() {
$("#k673f4141ea127b").contents().eq(1).wrap('<span class="annotation" />');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="metadata-entry" id="k673f4141ea127b">
<span class="generated" id="bcf5791f3bcca26">Publication date (<span class="data" id="caa7b9266191929">collection</span>): </span>
2003
</p>
At the end my solution is in this Fiddle.
Generalizing:
var element = document.getElementById(id);
var totalText = element.textContent;
var toFindText = totalText.substring(start,end);
var toReplaceText = "<span class='annotation'>"+toFindText+"</span>";
element.innerHTML = element.innerHTML.replace(toFindText, toReplaceText);
Hope it could help someone else.
Note: This don't check if two or more annotations refers to the same node, I'm working on it right now.
I am trying to take input from a number field and display it somewhere else on the page.
Here is my HTML
<input id="dollar" type="text" name="mytextfield2" onkeyup="updateDollarDisplay();">
<div id="dollarValue"></div>
and my javascript
function convertDigitsToArray(number){
var s = parseInt(number).toString(10).split("").map(Number);
return s;
}
function updateDollarDisplay() {
var amount = $('#dollar').value;
var a = convertDigitsToArray(amount);
console.log(a[0]);
$('#dollarValue').text(a[0]);
}
Running the exact code in a javascript interpreter works fine, it gives me each digit as an element in the array. When I try to do the same through the HTML page it gives me NaN each time. Any ideas?
Fiddle here: http://jsfiddle.net/7mzo8eb5/2/ I'd like it to show to input in the grayed div on each input.
The problem is with var amount = $('#dollar').value;
value is not an attribute, but val is a function. Should be: var amount = $('#dollar').val();
Simply can't figure out what I am doing wrong. I want to get the newly inserted data with jQuery when a user leaves the input field.
<textarea rows="3" id="textArea" data-atr="23,mytest,se"></textarea>
It work if I have something predefined text in the box, but not if it's just inserted text.
Here is what i have done so far:
$(document).ready(function() {
$("#textArea").blur(function(){
var atr = $("#textArea").data("atr");
var temp = new Array();
temp = atr.split(",");
var thisText = $("#textArea").html();
console.log(temp[0]+' - '+temp[1]+' - '+temp[2]+' - '+thisText);
});
});
My console log looks like this after I have written something into the field:
23 - mytest - se -
The inputted text is not there? What am I doing wrong?
Any help is appreciated and thanks in advance :-)
Please use val() instead of html().
Your existing code..
var thisText = $("#textArea").html();
You should use..
var thisText = $("#textArea").val();
Am now facing an other challenge. Some parts of my html code has the following lines:
<div class="action-body flooded"><p>(In <span class="error">[82681]</span>) refs AGLBD-16096<br/></div>
I have to get the number with-in the [] and then replace it with a hyperlink. I have tried using document.getElementsByClassName('error') but its not working. how can I make it work? and i would also need to iterate in a loop to replace all such numbers if there are more than one in []. e.g: [123] [234] [345]...
This is all what I have written till now with pimvdb's help:
<script type="text/javascript">
var bodyText = document.getElementById('body').innerHTML;
var pattern = /\[.*?\]/g;
var replaceText = "Pradeep";
document.getElementById('body').innerHTML = bodyText.replace(pattern, replaceText);
</script>
This JSFiddle does what you need: http://jsfiddle.net/TNyms/
When you replace getElementById('body') with document.body, the code works for me.
var body = document.body;
var link = "Pradeep";
body.innerHTML = body.innerHTML.replace(/\[.*?\]/g, link);
That replaces all IDs in this with links:
<div class="action-body flooded">
<p>(In
<span class="error">[82681]</span>) refs
AGLBD-16096
<br/>
</div>
<div>[123][abcd]</div>
<div>[456]</div>
<div>[789]</div>
Outputs:
(In Pradeep) refs AGLBD-16096
PradeepPradeep
Pradeep
Pradeep
Try it with this fiddle.
Your question appears to be related to what is asked in the below link. You may refer this
Replace number in a string using regex or something else