Javascript - Getting the first character of my string - error - javascript

can you tell me why the console says that it is not a function?
var firstAuthorName = document.getElementById("firstAuthorName");
var firstCharacter = console.log(firstAuthorName.slice(0,1));
then I get the text by this:
div.innerHTML += firstCharacter.value + ", " + firstAuthorInitials.value + ", " + firstAuthorSurname.value + ". ";
So the console says: "Uncaught TypeError: firstAuthorName.slice is not a function"

You need to access the contents of the HTML element and get the first character of that. You are attempting to get the first letter from the HTML DOM object itself, not the content of the object.
There are 3 standard ways to extract content of an element and which
you use depends on the kind of element you have and the kind of
content it contains:
1a. value : If the element is a form-field (radio button, checkbox,
text box, etc.) value is always used to get the value being held
in form-field.
1b. value is also used to obtain the value of an HTML element's attribute as in:
var src = document.querySelector("img").attributes[0].value;
console.log("The value of the \"src\" attribute of the image is: " + src);
<img src="images/someImage.jpg">
For non-form field elements, you can use textContent or innerHTML.
textContent just gets the characters that are the contents of an element (minus any HTML). If the element only contains
human consumable text, this is most-likely what you'll want.
innerHTML gets the content of the element, including any HTML CONTENT. Use this when the element in question contains HTML content
that you want as HTML, rather than text. While using innerHTML
instead of textContent works, it is a slightly more expensive
operation to perform because you are asking the HTML parser to parse
the contents, so don't use innerHTML on non-HTML content.
Here's a sample of all 3 of the above used correctly:
window.addEventListener("DOMContentLoaded", function(){
document.querySelector("button").addEventListener("click", function(){
var input = document.getElementById("txtTest");
var parent = document.getElementById("parent");
// textContent will get the text characters as they are:
var textOnly = console.log("textContent of parent div is: " + parent.textContent);
// innerHTML will get the content of the element but will parse its HTML:
var htmlContent = console.log("innerHTML of parent div is: " + parent.innerHTML);
// value is ONLY for form-field elements:
console.log("The value of the div is: " + parent.value); // undefined
console.log("The value of the textbox is: " + input.value);
});
});
<input id="txtTest" type="text" placeholder="type in me and then click the button">
<div id="parent">
<p>Nested child HTML</p>
</div>
<button>Click me to get results</button>
So, if your scenario is that the content is in, say a textbox, your solution would be to use value, like this:
var firstAuthorName = document.getElementById("firstAuthorName");
var button = document.querySelector("button");
button.addEventListener("click", function(){
console.log("The first character in the textbox is: " + firstAuthorName.value.slice(0,1));
});
<input id="firstAuthorName" type="text" placeholder="type in me and then click the button">
<button>Click Me</button>

Related

Get data-value from element in another file with jQuery

So basically I have some elements with some data-values in a file . I want to dynamically create links to them using those data-values to type the text, href etc.
For example, I have two divs, id'ed firstand second. They have importance values, respectively "most important" and "least important".
I want to create two links to them, with the phrase "This is a link to the most/least important div" using JavaScript/jQuery. Below is a non-working example.
File a.html (ommiting headings and such, ofc):
<div id='first' data-importance='most important'>This is the first div.</div>
<div id='second' data-importance='least important'>This is the second div.</div>
File b.html:
<p><a class='makelink' data-linkto='first'></a></p>
<p><a class='makelink' data-linkto='second'></a></p>
$(`.makelink`).each( function(){
var target = $(this).data('linkto');
$(this).attr('href','b.html#' + target);
var imp = $('b.html #' + target).data('importance');
$(this).html('Link to the ' + imp + ' div');
});
However nothing happens. Any help is appreciated.
Your code seems correct except the selector should be inside quote and the string generated in the html() is not properly formatted:
$('.makelink').each( function(){ // Enclosed the selector with single/double qoute
var target = $(this).data('linkto');
$(this).attr('href','#' + target);
var imp = $('#' + target).data('importance');
$(this).html('Link to the '+ imp + ' div'); // concatenate the string with the variable using +
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='first' data-importance='most important'>This is the first div.</div>
<div id='second' data-importance='least important'>This is the second div.</div>
<p><a class='makelink' data-linkto='first'></a></p>
<p><a class='makelink' data-linkto='second'></a></p>

jQuery .html() function removing text

I am trying to edit the div's text, but when i use my function to update the rowcount, everytime the text vanihes completely. Would by nice if you could also explain why.
Thanks in advance.
My update function:
var rowCountF = $('#tablef tr').length;
var rowCountV = $('#tablev tr').length;
var ftext = "Teilnehmer (" + String(rowCountF) + ")";
var vtext = "Teilnehmer (" + String(rowCountV) + ")";
$("#divf").html(ftext);
$("#divv").html(vtext);
My div layer:
<div id="divf"class="tableheader"> <h2>Teilnehmer</h2> </div>
Code for divf:
<div id="divf"class="tableheader"> <h2>Teilnehmer</h2> </div>
You are actually replacing the contents of the div itself with your text. This means the heading disappears and there is only plain text.
Probably you wanted to replace the heading contents:
$("#divf h2").html(ftext);
$("#divv h2").html(vtext);
This will select the h2 elements inside the divs and hence will update only the text inside the headings.
The result will look like the following:
<div id="divf"class="tableheader"> <h2>Teilnehmer (987)</h2> </div>
<div id="divf"class="tableheader"> <h2>Teilnehmer (123)</h2> </div>
.html() sets the HTML, meaning it replaces anything that's currently there. If you want to add to the HTML, you'll need to set the HTML to what's already there plus what you're adding, like so:
var rowCountF = $('#tablef tr').length;
var rowCountV = $('#tablev tr').length;
var ftext = "Teilnehmer (" + rowCountF + ")";
var vtext = "Teilnehmer (" + rowCountV + ")";
//Get already-existing HTML
var divfHtml = $("#divf").html();
var divvHtml = $("#divv").html();
//Set the new HTML to the existing + the new text
$("#divf").html(divfHtml + ftext);
$("#divv").html(divvHtml + vtext);
If you only want to replace the heading, then just target the <h2> as Martin Zikmund suggested in his answer.
You need to reference the h2 for the div. using .html() will replace ALL of the html inside the #divf which in this case means it will replace the h2
$("#divf h2").html(ftext);
$("#divv h2").html(vtext);
Example: https://jsfiddle.net/qhef0toc/3/

getting the innerHTML after finding the innerText

I have a RegEx to find the part of the text I want :
var re = RegExp("(?:^\\W*|(" + motBefore.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + ")\\W+)" + motErreur.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "(?:\\W+(" + motAfter.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + ")|\\W*$)", "g");
var resultMatch = document.getElementById('edth_corps').innerText.match(re);
Like this I can retrieve back the part of the text I need to modify with the punctuation. The trouble I get from here is to retrieve the innerHtml of this so I can get if in this part there is tag around the "motErreur".
I need to have to innerHTML because the purpose of my function is to wrap a span around the motErreur but this :
var reInner = resultMatch[0].replace(new RegExp("\\b" + motErreur + "\\b", "gi"), '<span id="'+nbId+'" class="erreurOrthographe" oncontextmenu="rightClickMustWork(event, this);return false">' + motErreur + '</span>');
document.getElementById('edth_corps').innerHTML = document.getElementById('edth_corps').innerHTML.replace(resultMatch, reInner);
does not work since between the innerText and the innerHTML it is possible to have tag already wrap around the part of text I get.
Example :
Input => this, tset, that; result : work fine because innerHTML and innerText are the same (no tag to mess up the search)
Input2 => this, <em>tset</em>, that; result : does not work since the innerText and the innerHTML are not the same (resultMatch is not the same as variable as what it is in the last replace).
I actually have no idea how to link these two thing correctly in the simplest way possible.
Configuration : javascript, compiled in quirks mode (only utility on IE, i don't care about other browser).
The trouble I get is that if there is already a span around motErreur
Assuming the innerHTML you get can only have a tag around your mot erreur you could check if there's a span this way :
if (theInnerHtml.firstChild) {
// It has at least one
var yourSpan = document.createElement('span');
// you set the innerHTML of yourSpan with the innerHTML of the child
// Ex <p> blablabla <em>motErreur</em> blabla </p>
// yourSpan will be "<span>motErreur</span>"
yourSpan.innerHTML = theInnerHtml.firstChild.innerHTML;
// you empty the innerHTML of your the child
// It will be <p> blablabla <em></em> blabla </p>
theInnerHTML.firstChil.innerHTML = "";
// Then you append your span to the firstChild
// It will be <p> blablabla <em><span>motErreur</span></em> blabla </p>
theInnerHTML.firstChild.appendChild(yourSpan):
}
This therefore implies that your innerHTML will only have 1 possible child, and that this child will be wrapping your motErreur

Javascript GetElementById Set Value To Input

I am trying to set value to my input but I want to do this while my data ends. As you know id must be unique in html. So i created an 'element' variable and I am increasing it.
I want to make my input text my model's CustomerName.
That's my code.
var element = 0;
var HTML = "";
while (element !== 5) {
HTML += "<input id=senderName" + element + " class=senderNameText type=text>";
document.getElementById("senderName" + element).value = "#Html.DisplayFor(model => model.CustomerName)";
element++;
}
div.innerHTML = HTML;
document.body.appendChild(div);
When I check it at console in Chrome it is written as "Cannot set property 'value' of null".
What should I do.
Thanks.
Your code should be like the following (note the quotes ' in creation of he new inputs are necessary) :
var element = 0;
var HTML = "";
while (element !== 5) {
div.innerHTML = "<input id='senderName" + element + "' class='senderNameText' type='text'>";
document.body.appendChild(div);
document.getElementById("senderName" + element).value = "#Html.DisplayFor(model => model.CustomerName)";
element++;
}
Now the problem come when you try to select new elements from the document and you're not yet append them so you get the message error that mean JS can't find any elements by the ids you're given.
So you should append the new HTML to the DOM inside loop.
Hope this helps.

type in empty divs while contenteditable = true?

why won't the cursor enter some of my divs when contenteditable is enabled?
also, why does my browser tell me there is nothing in the div when there is clearly a space character in it?!
var div = '<div> </div>';
div.innerHTML = undefined
What gives?
contenteditable does not apply to empty elements, so you may want to insert a non-breaking-space character into the empty elements you want to be able to edit
the non-breaking-space " " will act as a character when left on its own,
whereas a whitespace " " will only count as a character if placed after another character
<div>" "</div> ----------------> innerHTML = undefined
<div>" "</div> --------> innerHTML =
the gray box around means its an html character
so make sure you insert a "&nbsp" and not a " "
var nbsp = " ",
div = document.getElementById('id');
div.innerHTML = nbsp
jquery works too
var div = $('div#id')
div.html(nbsp1)

Categories