My HTML looks like this:
<div class="col-md-2" id="myName1">
<p>
Get This Text
</p>
</div>
The question is how do I get the text "Get this Text"
Something like this, but getting that text which is wrapped in the p and a tags:
function () {
return document.getElementById('TextID');
}
You can search for the first p inside your myName1 element, then the first a within that.
var e = document.getElementById('myName1').
getElementsByTagName('p')[0].
getElementsByTagName('a')[0];
var theText = e.innerHTML;
console.log(theText);
// or, in sufficiently-modern browsers
e = document.querySelector('#myName1 p a');
theText = e.innerHTML;
console.log( theText );
<div class="col-md-2" id="myName1">
<p>
Get This Text
</p>
</div>
Try adding the following in your function:
return document.querySelector('#myName1 p a').innerHTML
Simply using document.getElementById('anchorID').text; assuming anchor has id of anchorID. The text property sets or returns the text content of a link.
EDIT 1 : If you are not able to add the ID, then you need to take long path by going to document.getElementByID and then reach to the element using the document.getElementsByTagName
var myAnchor = document.getElementById("myName1").getElementsByTagName('p')[0].getElementsByTagName('a')[0];
console.log(myAnchor.text);
<div class="col-md-2" id="myName1">
<p>
<a id="anchorID" href="/something/121212">Get This Text</a>
</p>
</div>
you can use the get element by tag name method, but it returns an array of results so you will have to consider that, in your example, this works...
var a=document.getElementById('myName1');
console.log(a.getElementsByTagName('p')[0].getElementsByTagName('a')[0].innerHTML);
<div class="col-md-2" id="myName1">
<p>
Get This Text
</p>
</div>
Check this code, you can use innerHtml attribute
<script>
function gettext()
{
return document.getElementById('link').innerHTML;
}
</script>
<div class="col-md-2" id="myName1">
<p>
Get This Text
</p>
</div>
<script>
alert(gettext());
</script>
Or if you are using JQuery
$("#myName1 p a").text();
Related
I try convert simple string to HTML object for process it with jQuery.
My code:
var old_code_text = $(invoice_template_id).html();
console.log("old text ="+old_code_text);
old_code_text=$(old_code_text);
console.log("old text2 ="+old_code_text.html());
My first alert show me:
old text =<div id="template_invoice">
<div id="first_head">
<div id="logo_invoice">
<img src="../../../images/invoice_logos/logo912131214.PNG" width="200px">
</div>
<div id="main_header_info">
....
....
</div>
</div>
But my second alert show me :
old text2 =
<div id="first_head">
<div id="logo_invoice">
<img src="../../../images/invoice_logos/logo912131214.PNG" width="200px">
</div>
<div id="main_header_info">
....
Then I use old_code_text like it:
old_code_text.find("#product_invoice_table tbody").empty();
I dont understand where is div with id template_invoice?
When I parse string this div always deleted.
Thanks.
wrap the container in a dummy p element tag and you will get the container HTML also
var old_code_text = $("#template_invoice").wrap("<p/>").parent().html()
console.log("old text ="+old_code_text);
I'm trying to retrieve the ID of one element, store it as a variable and then use that ID value to interact with other elements in that section with the same ID.
<div class="mainContent">
<div class="articleContent">
<h1>header1</h1>
<p class="articlePara" id="one">para1</p>
</div>
<div class="articleFooter" id="one" onclick="readMore()">
</div>
</div>
<div class="mainContent">
<div class="articleContent">
<h1>header2</h1>
<p class="articlePara" id="two">para2</p>
</div>
<div class="articleFooter" id="two" onclick="readMore()">
</div>
</div>
And then the JS/jQuery
function readMore() {
var subID = event.target.id;
var newTarget = document.getElementById(subID).getElementsByClassName("articlePara");
alert(newTarget.id);
}
At this point I'm only trying to display the ID of the selected element but it is returning undefined and in most cases people seem to notice that jQuery is getting confused because of the differences between DOM variables and jQuery ones.
jsfiddle: https://jsfiddle.net/dr0f2nu3/
To be completely clear, I want to be able to click on one element, retrieve the ID and then select an element in the family of that clicked element using that ID value.
just remove the getElementsByClassName("articlePara"); in end of the newTarget .already you are call the element with id alert the element of the id is same with target.id
function readMore() {
var subID = event.target.id;
var newTarget = $('[id='+subID+'][class="articlePara"]')
console.log(newTarget.attr('id'));
console.log(newTarget.length);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mainContent">
<div class="articleContent">
<h1>header</h1>
<p class="articlePara" id="one"></p>
</div>
<div class="articleFooter" id="one" onclick="readMore()">click
</div>
</div>
As you have read before, you should keep your id's unique, and you should avoid using onclick in html, but you could do it like this.
With querySelector you get the element and then with parentElement you can retrieve the parent of that element.
function readMore(el) {
var articleFooterId = el.id;
var articlePara = document.querySelector(".articleContent #"+articleFooterId);
var articleContent = articlePara.parentElement;
console.log('articleFooter', articleFooterId);
console.log('articlePara', articlePara);
console.log('articleContent', articleContent);
}
In your html you can return the 'this' object back to the function by doing readMore(this).
<div class="mainContent">
<div class="articleContent">
<h1>header1</h1>
<p class="articlePara" id="one">para1</p>
</div>
<div class="articleFooter" id="one" onclick="readMore(this)">footertext</div>
</div>
<div class="mainContent">
<div class="articleContent">
<h1>header2</h1>
<p class="articlePara" id="two">para2</p>
</div>
<div class="articleFooter" id="two" onclick="readMore(this)">footertext</div>
</div>
jsfiddle
if you're using Jquery:
$(function () {
$('div.articleFooter').click(function () {
var para = $(this).prev().find('p.articlePara').text();
alert('T:' + para);
});
})
$('.articleFooter').click(function() {
var b=subId; //can be any
var a="p[id="+b+"]"+"[class='articlePara']";
$(a).something;
});
You have forgotten to pass in event as parameter in your onclick= call in html.
In your javascript, you need to include event in the parenthesis as well.
window.readMore = function(event) {...}
if you write document.getElementById(subID).getElementsByClassName("articlePara"); That's saying you want to get your clicked element's CHILD elements that have class equal to articlePara . There is none. So you get undefined.
If you want to find all element with a ID one and a class articlePara, it can be done easily with jQuery:
newtarget = $("#one.articlePara");
You can insert a line: debugger; in your onclick handler function to trigger the browser's debugging tool and inspect the values of variables. Then you will know whether you are getting what you want.
SOMEUSERNAME
<div class="col s9">
<p id="p_50">Some message</p>
<br>
<br>
<span class="forumtools">
<strong>
<a onclick="quote(\'p#p_50\')">Quote</a>
</strong>
<span class="right">Written SOMEDATE</span>
</span>
</div>
JQuery/JS:
function quote(post) { $(post).text(); }
This works to fetch the posts message, but how do I go about finding the Username?
I have tried using $(post).prev('a').text();, and $(post).parent().prev('a').text();, but nothing seems to work.
You can do it without jQuery. If possible, change the html and pass the current link to the function, like this:
<a onclick="quote(\'p#p_50\', this)">Quote</a>
Then you can just search through all links:
function quote(str, currentLink) {
var allLinks = document.getElementsByTagName("a"); // get all links in document
var index = allLinks.indexOf(currentLink);
if (index > 0) {
var prevLink = allLinks[index-1];
console.log(prevLink); // log it to browser console
} else {
console.log("there is no previous link");
}
}
By looking at the DOM structure, it should work with $(post).parent().prev().text().
Alternative way, how about you wrap all of them with <div>, like this: XD
<div id="message1">
SOMEUSERNAME
<div class="col s9">
<p id="p_50">Some message</p>
<br>
<br>
<span class="forumtools">
<strong>
<a onclick="quote(\'#message1\')">Quote</a> //change to wrapper id
</strong>
<span class="right">Written SOMEDATE</span>
</span>
</div>
</div>
then to get the post text: $(post).find('#p_50').text();
to get the username: $(post).find('a:first').text();
Looking at your sample HTML, if you're at p, just go to parent element and get the closest a and you should be fine:
function quote(post) {
var post = $(post).text();
var user = $(post).parent().closest('a').text();
}
Perhaps using parent() and then previous()
var ancortext = $(post).parent().prev().text();
A function example below.
function username(post) {
return $(post).parent().prev().text();
}
Note: This smells to me, your code is very much tied into the structure of the HTML this way. If you alter the HTML, chances are your javascript will break.
I have copied your code into my own HTML document, and confirmed that the jquery method calls above output the desired result. If you are not, then something is different with your source HTML and the source that you posted, or your jquery functions differ from the ones stated in this answer :)
your onclick attribute is wrong,because onclick accept javascript,so the value could be support js,then onclick="quote('p#p50')".
function quote(post) {
var subject = $(post).text();
var user=$(post).parent().prev('a').text();
console.log('posted '+subject+' by '+user);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
SOMEUSERNAME
<div class="col s9">
<p id="p_50">Some message</p>
<br>
<br>
<span class="forumtools">
<strong>
<a onclick="quote('p#p_50')">Quote</a>
</strong>
<span class="right">Written SOMEDATE</span>
</span>
</div>
In my use case, I am trying to get value from dynamically generated hidden field in JQuery. When I click the button for that iteration I should get the value for the hidden field belongs to that iteration. But I am not able to get it. It is giving the value as 'undefined'
HTML:
<div class="comment-list-new" style= "max-height: 660px !important;overflow-y: scroll;">
<h5>Discussion Board</h5>
<ol>
{{ if .ViewData.Questions }}
{{ range .ViewData.Questions }}
<li>
<p id="question_id" class="question_id_val" hidden>{{.QuestionId}}</p>
<div class="q-comment">
<div class="qanda questiondiv" id="questionarea" name="questionarea">
<div>
<div id="topic" class="upvote pull-left">
<a class="upvote"></a>
<span class="count">3</span>
<a class="downvote"></a>
</div>
<div >
<div class="qanda-info">
<h6><p id="quest_title">{{.QuestionTitle}}</p></h6>
</div>
<p id="quest_text">{{.QuestionText}}</p>
</div>
</div >
<div class="qanda-info">
<div class="user-info">
<img src="/resources/img/team-small-2.png" />
</div>
<h6>{{.UserId}}</h6>
<span class="date alt-font sub">{{.DateCreated}}</span>
<a id="answertext" name ="answertext" type="submit" class="link-text answerbutton">Answer</a>
</div>
</div>
</div>
</li><!--end of individual question-->
{{ end }}
{{ end }}
</ol>
</div><!--end of comments list-->
JS:
$('.questiondiv').on('click', '.submitanswerbutton', function() {
console.log("In submit button");
var question_id = $(this).closest('.question_id_val').val();
var answer_text = $('.answertext_val').val();
console.log(question_id);
console.log(answer_text);
$.getJSON("/submitanswer?question_id="+question_id+"&answer="+answer_text, function(data) {
console.log("answer Response"+data);
newQuestion = "<li><div class='q-comment'><div class='qanda' id='questionarea' name='questionarea'><div><div id='topic' class='upvote pull-left'><a class='upvote'></a><span class='count'>0</span><a class='downvote'></a></div><div ><div class='qanda-info'><h6><p id='quest_title'>"+title+"</p></h6></div><p id='quest_text'>"+desc+"</p></div></div ><div class='qanda-info'><div class='user-info'><img src='/resources/img/team-small-2.png' /></div><h6>Chip Mayer</h6><span class='date alt-font sub'>September 17 2014</span><a id='answertext' name ='answertext' type='submit' class='link-text'>Answer</a></div></div></div></li>";
$('ol').append(newQuestion);
});
});
In the above code I am trying to get the value for the hidden field question_id_val.
Could anyone help me with this?
Use closest() to get a reference to the outer container (li) and then use find() method to get the hidden field.
var question_id = $(this).closest('li').find('.question_id_val').val();
val() method works for usually input form fields(textbox,hidden fields etc..) .So you need to make sure your element is a valid form field in your page.
<input type="hidden" id="question_id" class="question_id_val" />
Or if you want to keep your p tag as it is, Use the html() or text() method to get the content of the p tag.
var question_id = $(this).closest('li').find('.question_id_val').text();
Remember, these method returns the text/html of all child content as well. So make sure to use it wisely.
val() should be used primarily in select, textarea and input elements.
For getting the inner text use html() or text()
var question_id = $(this).closest('.question_id_val').html();
or
var question_id = $(this).closest('.question_id_val').text();
If you know a css selector id or class I don't see problem why you can't do something like this:
var question_id = $('#question_id').text();
Or
var question_id = $('.question_id_val').text();
I need something in jQuery but can't figure it out.
I got this html:
<h2>My Name 1</h2>
<h2>My Name 2</h2>
// many more
In jQuery I want to get the content of this `h2' and need that for:
<h2>My Name 1</h2>
This is working:
jQuery(".content h2").prepend("<a href=''>").append("</a>");
But the href has to be based on its content... How to do that?
Thanks!
You can't append a chunk of HTML element like the half of a tag. Browser fixes such an invalid HTML and won't render it.
Use wrapInner method:
$('.content h2').wrapInner('');
If link href attribute somehow depends on actual h2 content then you should use function as wrapInner arguments, see Rory McCrossan's answer. For example to set href to be the same as h2 content it can be:
$('h2').wrapInner(function() {
return '';
});
I'm not sure that what you have is working as you expect because you can only append whole elements. Your current code would end up with something like this:
<h2>
<a href=''></a>
My name 1
<a></a>
</h2>
Given that you want to effectively wrap the text of the h2 in an a element you can use wrapInner() with a handler function containing the logic to set the href. Try this:
jQuery(".content h2").wrapInner(function() {
var href = 'foo.php'; // your logic here
return '';
});
Example fiddle
$(function () {
$(".content h2").each(function (n) {
var x =$('h2').eq(n).text();
var y = x.replace(/\s/g, '');
$(".content h2").eq(n).empty().append(""+x+"");
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="content">
<h2>My Names 1</h2>
<h2>My Names 2</h2>
<h2>My Names 3</h2>
<h2>My Names 4</h2>
<h2>My Names 5</h2>
</div>
Blockquote
So, grab the content of H2 and then append A with href and text as the grabbed content.
var h2Text = $(".content h2").text();
$(".content h2").empty().append( $("<a/>", { href: h2Text, text: h2Text }));
Try this..
$(document).ready(function(){
var href = 'test.html';
jQuery(".content h2").prepend("<a href='"+href+"'>").append("</a>");
});