Verify whether the div already includes a particular item

I am currently working on an angular project where I need a button to add a blockquote within a div, but only if the blockquote is not already present in the HTML structure.

My initial approach was to search for the specific string

<blockquote id='myBlockquote'>
within the HTML content using the code snippet below, however, it does not seem to be functioning as expected:

if ((myHTML.indexOf('<blockquote id="myBlockquote">') = -1)) {
  myHTML.append('some HTML');
}

I'm clearly missing something here. Can someone point me in the right direction?

Thanks!

Answer №1

One way to ensure that your desired element exists is by checking its length with the use of .length, and then proceed to append it.

if(myHTML.find('#myBlockquote').length > 0) {
  myHTML.append('some more HTML');
}

Answer №2

It is recommended not to manipulate the DOM directly from the controller as it should be handled by the view.

To achieve this, create an array within the scope that contains the blockquotes:

$scope.blockquotes = [{id: 1, text: "This is a blockquote"}, {id: 2, text: "This is a blockquote"}, {id: 3, text: "This is a blockquote"}];

You can also create a function that is triggered on click to check if a particular user has already added a blockquote:

$scope.addBlockquote = function(userId) {
  var found = false;
  for(var i = 0; i < $scope.blockquotes.length; i++) {
    if ($scope.blockquotes[i].id == userId) {
      found = true;
      break;
    }
  }
}

In your view or HTML template, loop through the blockquotes array and display them accordingly:

<blockquote ng-repeat="quote in blockquotes">{{quote.text}}</blockquote>

Answer №3

It appears that myHTML is a string and not a DOM object. One way to check for the existence of an element within it is by converting the string to HTML and then searching for the element:

var elements = $(myHTML);
if(!$('#myBlockquote', elements).length){
   //The element does not exist.
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to enlarge the size of specific letters in HTML

I am looking to enhance the values of C and I. In addition, I am utilizing ::first-text{}. This is currently functioning well. Now, the question arises - how can I elevate the value of I. <p>Creating and Implementing</p> <center> < ...

Using CSS Grid to Create Three Rows of Equal Height

I am facing an issue with my vertical menu that stretches 100% height. The rows inside this menu need to have equal height and be stretched to fit the container. Additionally, I noticed that adding a button seems to drop the container slightly below the pa ...

Header and footer on iPad are not extending to full width even when set to 100% width

Upon viewing this link on an iPad, you may observe that the header does not span the full width of the page, leaving a noticeable pixel gap on the right side. The same issue is present with the footer. It is puzzling to me because both elements are set to ...

Revise website design to adjust dynamically according to screen dimensions

Currently, I am working on a school project with a website created by former students. Unfortunately, I have limited knowledge of HTML and CSS which has made it challenging for me to ensure the site is mobile-friendly. There are issues such as text overflo ...

The location of the CHROMEDRIVER for Node.js with Selenium

After trying "npm install selenium-webdriver", I am still encountering the error message below. Can anyone provide guidance on where the path is supposed to be located? Error: The ChromeDriver could not be found on the current PATH. Please download the ...

Creating a list element after clicking in ReactJS is achieved by using event handlers in

I have buttons and inputs that I want to use to generate a list item in the ul section at the end of my code. However, despite adding functions to handle this feature, it still doesn't work as intended. import { useState } from 'react'; impo ...

Troubleshooting problem in Java related to encoding with XMLHttpRequest

Currently, I am utilizing XMLHttpRequest for an ajax call to my server. Let's consider the call: http = new XMLHTTPRequest(); var url = "http://app:8080/search.action?value=ñ" http.open("GET",url,true); http.setRequestHeader("Content-type", "applica ...

Utilizing an array interpolation method within a Postgres query in JavaScript

Currently, I am working on a project using Node.js and relying on the 'pg' npm module. My main goal is to compare whether an array's contents are present within another array stored in a Postgres table. The order of the elements does not mat ...

Locate the specific version of a JavaScript library within compiled JS files

The dist folder houses the results of running npm install. If I don't have access to the original package.json file used during the compilation of the distributable, how can I determine the version of a particular library that was utilized in the ins ...

Executing PHP script within a Node.js socket server program

I have a JavaScript file running a normal TCP socket using node.js. Before sending a response back to the client, I need to validate the data using some PHP (MySQL) code. Can someone guide me on executing this PHP code inside the JavaScript file? Most of t ...

Incorporating Angular into the script code of the extension content

I am looking to customize text fields on a website using a chrome-extension. However, the website is built with Angular, so I need to modify the text fields using Angular code. To incorporate Angular in my extension's scope, I am attempting to declar ...

Determine the item in a collection of objects that contains a specific key

What is the most efficient method for locating an object by a specific key in JS when given an array of objects? Utilizing jQuery and underscoreJS is acceptable. I am simply seeking the simplest solution with minimal code. Illustration: Suppose we have a ...

Can DOM addEventListener be effectively implemented alongside JQuery events?

In my current project, I am utilizing Bootstrap4 alpha version. As part of my investigations, I am attempting to capture a JQuery event using the DOM's addEventListener() method. The specific event is triggered by Bootstrap through the use of the JQu ...

Elevate a specific element above others and stagger the positioning of certain elements by pushing them downwards

Take a look at this image to see the issue visually. I'm facing a problem with a div that contains a list displayed below a text field. It's essentially a simulated Combo-box that uses a text element and JavaScript. The issue is that when someon ...

Calculate the total amount based on the selected value from the radio button

For example, radiobutton A = value X, radiobutton B = value Y. Below is the code snippet I am utilizing: Javascript file: <script type="text/javascript" $(document).ready(function () { $("div[data-role='footer']").prepend(' ...

Transitioning to a bootstrap or fluid design from a foundation of simple HTML and CSS

Although I am not a web designer by trade, I have a background in statistics and am currently working on building a website. I have sketched out the layout structure I desire using basic html and simple css to kick things off. However, upon further explora ...

Certain functionalities of Bootstrap may not be functioning properly within an Angular 6 project

I followed a tutorial from a source to integrate bootstrap into my newly developed angular 6 project. After compiling, I encountered no errors either in the 'ng console' or in the browser's developer tools. Although the buttons are well-co ...

"Exploring the best method to send an AJAX callback to a particular div that has been dynamically generated using

Exploring a specific scenario: Below you'll find some HTML code representing rating stars generated through a PHP foreach loop. Each div with the class rating has a unique $file_id value. <div class="rating" data-rating="<?php echo $round;?> ...

How can I adjust the size and alignment of each line within a single cell in an HTML table?

<!DOCTYPE html> <html> <head> <title></title> <meta charset="UTF-8"> <style> .chess-board { border-spacing: 0; border-collapse: collapse; } .chess-board ...

How to insert a value using jQuery Minicolors in an HTML document?

While I found similar topics on Stackoverflow, none exactly match my issue. I am currently incorporating jquery Minicolors into my project: https://github.com/claviska/jquery-miniColors/ Everything is functioning properly, but I simply need to accomplish ...