injecting element using the document.getElementById is not working in Javascript - javascript

I have written a small javascript code and now need to inject the result into my HTML. I have inspected the windows element and even copied the specific selector for that element but it still doesn't inject the answer into it. I am trying to insert it into the span tag in the HTML code.
const str = new Date().toLocaleString('en-US', { timeZone: 'Asia/Jakarta' });
console.log(str);
document.getElementById('#us').textContent = str
<div class="header-button-item js-item-menu">
<i class="zmdi zmdi-settings"></i>
<div class="setting-dropdown js-dropdown">
<div class="account-dropdown__body">
<div class="account-dropdown__item">
<i class="zmdi zmdi-email"></i>America Time - <span id="us"></span>
</div>
</div>
</div>
</div>

You could try this:
const str = new Date().toLocaleString('en-US', { timeZone: 'Asia/Jakarta' });
console.log(str);
document.getElementById('us').innerHTML = str

Thanks to you all, I was able to solve it after going through all the comments.
my mistake was using the # together with the getElementById. So, I had to remove the # which then made it work well.
But if you need to use the # then you can go with something like getSelector.
document.getElementById('us').textContent = us_time
or
document.getSelector('#us').textContent = us_time

You're getting confused with querySelector.
const str = new Date().toLocaleString('en-US', { timeZone: 'Asia/Jakarta' });
console.log(str);
document.querySelector('#us').textContent = str
<div class="header-button-item js-item-menu">
<i class="zmdi zmdi-settings"></i>
<div class="setting-dropdown js-dropdown">
<div class="account-dropdown__body">
<div class="account-dropdown__item">
<i class="zmdi zmdi-email"></i>America Time - <span id="us"></span>
</div>
</div>
</div>
</div>

Related

How to prevent replacing HTML elements when using innerHTML?

I'm matching HTML elements based on their textContent. Then surronding that match with <strong> tags:
const element = [...document.querySelectorAll('a')]
.find(element => element.textContent.match('b'))
element.innerHTML = element.innerHTML.replace('b', '<strong>$&</strong>')
<a href="#">
<br>
<h3>blog</h3>
</a>
There's a problem, though. The code also matches HTML elements. So I get this:
<a href="#">
<<strong>b</strong>r>
<h3>blog</h3>
</a>
Instead of the desired result:
<a href="#">
<br>
<h3>blog</h3>
</a>
How to change my code so it doesn't match HTML elements? Only the text inside them?
Iterate over the children elements of your anchors and reset the HTML based on whether the textContent of the element contains "b".
Note: find will only find the first instance of the thing you're looking for. You need to explicitly iterate over all of the things.
The find() method returns the value of the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.
const elements = [...document.querySelectorAll('a')];
function embolden(elements, str) {
elements.forEach(element => {
[...element.children].forEach(child => {
if (child.textContent.includes('b')) {
child.innerHTML = child.textContent.replace('b', '<strong>b</strong>');
}
});
});
}
embolden(elements, 'b');
<a href="#">
<br>
<p>blog</p>
</a>
<a href="#">
<br>
<p>blog</p>
<p>Peterborough</p>
</a>
Use innerText instead of innerHTML to match. Insert the replaced values in the innerHTML
const element = [...document.querySelectorAll('#example')]
.find(element => element.textContent.match('b'))
element.innerHTML = element.innerText.replace('b', '<strong>$&</strong>')
<div id="example">
<div>This is some text.</div>
<br>
<div> This is part of the body </div>
</div>
You can use this regex: /(?!<[^>]+)b(?![^<]+>)/g
const element = [...document.querySelectorAll('a')]
.find(element => element.textContent.match('b'))
const string = "b";
const reg = new RegExp("(?!<[^>]+)" + string + "(?![^<]+>)", "g");
element.innerHTML = element.innerHTML.replace(reg, '<mark>$&</mark>')
mark
{
background-color: lightgreen;
}
<a href="#">
<br>
<h3 title="attributes are not affected bbbb">blog hover blog</h3>
</a>

How i can check if a <P> inside a <Div> contain data

I have the following field inside my SharePoint office 365 page:-
here is the related markup:-
<div class="ms-rtestate-write ms-rteflags-0 ms-rtestate-field" id="ProjectClosureSummary_cdd30532-e128-4dcd-b9bd-baf3e12a4c04_$TextField_inplacerte"
role="textbox" aria-haspopup="true"
aria-labelledby="ProjectClosureSummary_cdd30532-e128-4dcd-b9bd-baf3e12a4c04_$TextField_inplacerte_label" style="min-height:84px" contenteditable="true"
aria-autocomplete="both" aria-multiline="true" rtedirty="true">
<p>
need to ge this text!!
<span id="ms-rterangecursor-start" rtenodeid="1">
</span>
<span id="ms-rterangecursor-end"></span><br>
</p>
</div>
now using javascript or jQuery i need to check if the field contain data? but i am not sure how i can get the text which is inside a <p> inside a <div>?
Maybe you could try something like this:
text = $('p').text();
Please take reference from below code:
var parentdiv = document.getElementById('parent');
var childNode = parentdiv.hasChildNodes() ? parentdiv.children[0] : ''
console.log(childNode.textContent || childNode.innerText);
<div id="parent"><p>hello world</p></div>

How to print hyperlinks inside <p> tag when databinding AngularJS

I'm using a controller to convert any web links inside an <input> tag, and show them in a <p> tag. I want it to show the links in a hyperlink format as in
https://www.w3schools.com is great but it shows
Here's my code,
my HTML
<div class="col-sm-10 col-sm-offset-1">
<div class="row" style=" margin-top:70px;">
<div id='dv1'>
<form>
<input ng-model="comment.txtcomment" id="txtcomment" style='width:500px' >
<button ng-click="addComment()" style='margin-top:10px;'>Post Comment</button>
</form>
<!--displaying comments-->
<h4>Comments</h4>
<p>{{myText}}</p>
</div>
<div></div>
my controller
(function(){
angular.module('StayFit')
.controller('CommentController',['$scope','$state','$http', function($scope,$state,$http){
$scope.user=JSON.parse(localStorage['User-Data']) || undefined;
console.log( $scope.user.data);
$scope.comment={};
$scope.addComment=function(){
var text=$scope.comment.txtcomment;
//this code will identify any links
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
var text1=text.replace(exp, "<a href='$1'>$1</a>");
var exp2 =/(^|[^\/])(www\.[\S]+(\b|$))/gim;
var val=text1.replace(exp2, '$1<a target="_blank" href="http://$2">$2</a>');
$scope.myText=val;
}//.error(function(error){console.log(error);});
}])}());
Tried using ng-binding-html, also doesn't work
You apparently want to use text as HTML, not text, so you need to use ngBindHtml.
Be aware that SCE comes into play as well, so you will have to use something like $scope.myTextVal = $sce.trustAsHtml(val);.

Selecting element with JS issue

Please help me to understand this. I have HTML code like this:
<div id="one">
<div>
<div>
<span class="spanone"></span>
<span class="spantwo"></span>
<div>
</div>
</div>
.
.(some other html of the page)
.
<sometag class="spanone"></sometag>
<someothertag class="spantwo"></someothertag>
And I basically want to target only the first <span> and the second by JS without touching the sometags elements. In other words the: <span class="spanone"> and <span class="spantwo">. And then I want to use innerHTML to replace the code with the one I want.
Thanks!
var spanone = document.querySelector('.span1');
var spantwo = document.querySelecftor('.span2');
spanone.innerHTML = "Replacement";
spantwo.innerHTML = "Replacement";
You can achieve this in a couple ways
Use id
<span class="spanone" id="myspan1"></span>
<span class="spantwo" id="myspan2"></span>
so in vanilla JS
var d = document;
d.getElementById('myspan1');
d.getElementById('myspan2');
or with classes
<span class="spanone myspans"></span>
<span class="spantwo myspans"></span>
and in your JS
d.querySelectorAll('.myspans')
This should work:
var spanone = document.querySelector('.spanone')[0];
var spantwo = document.querySelecftor('.spantwo')[0];

How to change date-value?

I have a following HTML but I am not able to change the value of date-value and title. Can you please suggest how to do this?
<a title="Date::04/08/2013">
<span class="name">Date::</span>
<span data-value="04/08/2013" class="value">04/16/2013</span>
</a>
Sorry for the incomplete question.
Value 04/16/2013 is assigned using jQuery but the title="Date::04/08/2013" and data-value="04/08/2013" doesn't changed. I want "Date::04/08/2013" should be "Date::04/16/2013" and data-value="04/08/2013" should be data-value="04/16/2013".
Thanks in advance.
I think you have this
<a title="Date::04/08/2013" id='date-link'>
<span id="date-title" class="name">Date::</span>
<span id="date-value" data-value="04/08/2013" class="value">04/16/2013</span>
</a>
and you want following
<a title="Date::04/16/2013" id='date-link'>
<span id="date-title" class="name">Date::</span>
<span id="date-value" data-value="04/16/2013" class="value">04/16/2013</span>
</a>
If so, you can try following
var dateTitle = jQuery("#date-title").html()
var dateValue = jQuery("#date-value").html()
jQuery('#date-link').attr('title', dateTitle+dateValue);
jQuery('#date-value').attr('data-value', dateValue);
You can create a html file with following code and check your own
<script src="http://code.jquery.com/jquery-1.7.2.min.js" type="text/javascript"></script>
<a title="Date::04/08/2013" id='date-link'>
<span id="date-title" class="name">Date::</span>
<span id="date-value" data-value="04/08/2013" class="value">04/16/2013</span>
</a>
Click Here
<script>
function abc() {
var dateTitle = jQuery("#date-title").html()
var dateValue = jQuery("#date-value").html()
jQuery('#date-link').attr('title', dateTitle+dateValue);
jQuery('#date-value').attr('data-value', dateValue);}
</script>
Try this :
$('span.value').attr("data-value", "04/16/2013")
.data("value") might not work, since value maps to something else.
Besides, try using some other keyword other than value, if possible.
html code:
<a title="Date" id="data">
<span class="name">Date::</span>
<span data-value="04/08/2013" class="value">04/16/2013</span>
</a>
js:
$("#data").find('span').attr("data-value", "04/16/2013");
try this u ll get data-value...
$('.value').attr('data-value',$('.value').html());
var value = $('.value').text();
$('.value').attr('data-value',value)

Categories

Resources